static final String url = "jdbc:mysql://localhost:3306/lib?useUnicode=true&characterEconding=UTF-8";
static final String user = "root";//自己的数据库的用户名
static final String password = "123456";//自己的数据库的密码
static Connection conn = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
//------------------------------------------------------------查询操作:
public User findUser(User user) {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
String sql = "select * from manager where name = ? and password = ? ";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
rs = ps.executeQuery();
try {
while (rs.next()) {
if (rs.getString("name").equals(user.getName())
&& rs.getString("password").equals(user.getPassword())) {
// 关闭数据库连接
ps.close();
rs.close();
conn.close();
//返回查询对象
return user;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
//------------------------------------------------------------插入操作(删除、修改除了sql不一样其他都一样):
public boolean saveUser(User user) {
boolean flag = false;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
String sql = "insert into manager(name,password,tel) values(?,?,?)";
int i = 0;
ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getTel());
i = ps.executeUpdate();
//i>0表示执行成功
if (i > 0) {
flag = true;
}
ps.close();
conn.close();
return flag;
}