1、连接数据库
MySQL com.mysql.jdbc.Driver , jdbc:mysql://localhost:3306/mydb
创建Connection,Statement对象:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
stat = con.createStatement();
2、执行SQL语句
StringBuffer SQL = new StringBuffer("select * from user where ");
String sign = "";
if(user.getID() > 0){
SQL.append("ID = " + user.getID());
sign = " and ";
}
if(user.getName() != null){
SQL.append(sign+"name = " + user.getName());
}
rs = stat.executeQuery(SQL.toString());
3、获取结果
while(rs.next()){
user.setID(rs.getLong("ID"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
ser.setRole(rs.getString("role"));
}
4、关闭连接
public void closeConnect(){
try{
if(!con.isClosed()){
con.close();
}
if(!stat.isClosed()){
stat.close();
}
if(!rs.isClosed()){
rs.close();
}
}
catch (SQLException e){
e.printStackTrace();
}
}