*****实体bean******
package com;
import java.io.Serializable;
@SuppressWarnings("serial")
public class UserInfoBean implements Serializable{
private int userId;
private String loginName;
private String loginPass;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getLoginPass() {
return loginPass;
}
public void setLoginPass(String loginPass) {
this.loginPass = loginPass;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
******数据库dao******
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDAO {
private static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String URL="jdbc:sqlserver://localhost:1433;databasename=restrant";
private static final String USER="sa";
private static final String PWD="sa";
/**
* 获得数据库连接
* @return 可用数据库连接
* @throws Exception
*/
public Connection getConn()throws Exception{
Class.forName(DRIVER);
return DriverManager.getConnection(URL,USER,PWD);
}
/**
* 释放资源
* @param rs 结果集
* @param ps 命令行对象
* @param conn 数据库连接
*/
public void closeAll(ResultSet rs,PreparedStatement ps,Connection conn){
try {
if(rs!=null)
rs.close();
if(ps!=null)
ps.close();
if(conn!=null)
conn.close();
} catch (SQLException e){
e.printStackTrace();
}
}
/**
* 可用执行增,删,改操作,不能用于查询
* @param sql 预编译的SQL语句
* @param param 预编译SQL语句中的‘?’参数的字符串数组
* @return 返回受影响的行数
*/
public int executeSql(String sql,String[] param){
Connection conn=null;
PreparedStatement ps=null;
int num=0;
try {
conn=getConn();
ps=conn.prepareStatement(sql);
if(param!=null){
for(int i=0;i<param.length;i++){
ps.setString(i+1, param[i]);
}
}
num=ps.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}finally{
closeAll(null, ps, conn);
}
return num;
}
}
******具体操作******
package com;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class UserManagerDAO extends BaseDAO {
public ArrayList<UserInfoBean> searchUser(){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
ArrayList<UserInfoBean> lists=new ArrayList<UserInfoBean>();
String sql="select * from userinfo";
try {
conn=getConn();
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
UserInfoBean u=new UserInfoBean();
u.setUserId(rs.getInt("userid"));
u.setLoginName(rs.getString("loginname"));
u.setLoginPass(rs.getString("loginpass"));
lists.add(u);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
closeAll(rs, ps, conn);
}
return lists;
}
}