Java之增删查改
开发工具与关键技术:MyEclipse 10/Java
作者:陈希雄
撰写时间:2019年07月05日
新增
//新增用户
@Override
public int userRegDao(User u) {
// 声明变量
int index = 0;
Connection conn=null;
// 加载驱动
Class.forName(driver);
// 获取连接对象 jdbc:mysql://localhost:3306/test
conn = DriverManager.getConnection(url, name, password); // 创建sql命令
String sql = "insert into u_user value(default,?,?,?,?,?)";
try {
// 创建 sql命令对象
ps = conn.prepareStatement(sql);
ps.setString(1, u.getUname());
ps.setString(2, u.getPwd());
ps.setInt(3,u.getAge());
ps.setString(4, u.getSex());
ps.setString(5, u.getBirth());
index = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return index;
}
查询
//查询所有用户
@Override
public List<User> userShowDao() {
//声明数据储存对象
List<User> list=null;
User u=null;
Connection conn=null;
// 加载驱动
Class.forName(driver);
// 获取连接对象 jdbc:mysql://localhost:3306/test
conn = DriverManager.getConnection(url, name, password); //创建命令
String sql="select * from u_user";
try {
//创建 sql命令对象
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
//给集合赋值
list=new ArrayList<User>();
//遍历执行结果
while(rs.next()){
//给变量赋值
u=new User();
u.setUid(rs.getInt("uid"));
u.setUname(rs.getString("uname"));
u.setPwd(rs.getString("pwd"));
u.setSex(rs.getString("sex"));
u.setAge(rs.getInt("age"));
u.setBirth(rs.getString("birth"));
list.add(u);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
修改
//根据用户ID修改用户密码
@Override
public int userChangePwdDao(String newPwd, int uid) {
//声明变量
int index=0;
Connection conn=null;
// 加载驱动
Class.forName(driver);
// 获取连接对象 jdbc:mysql://localhost:3306/test
conn = DriverManager.getConnection(url, name, password); //创建sql命令
String sql="update u_user set pwd=? where uid=?";
try {
//创建 sql命令对象
ps=conn.prepareStatement(sql);
//给占位符赋值
ps.setString(1, newPwd);
ps.setInt(2, uid);
//执行
index=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭资源
Jdbc.close(conn, ps, rs);
}
return index;
}
删除
//删除
public static Integer detele(String sql, String newPwd, int uid){
//返回值
int index=0;
Connection conn=null;
// 加载驱动
Class.forName(driver);
// 获取连接对象 jdbc:mysql://localhost:3306/test
conn = DriverManager.getConnection(url, name, password); try {
ps=con.prepareStatement(sql);
//给占位符赋值
ps.setString(1, newPwd);
ps.setInt(2, uid);
//执行
index=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DbUilt.close(con, ps, rs);
}
return index;
}
总结:executeUpdate() 对于增删改的操作,executeQuery() 对于查询操作