备注:承接java-JDBC(连接数据库)博文
1.首先现在数据库建立数据表
2. java实现数据库中的增加数据
//添加信息
public int AddUser(UserInfo ui);
//修改信息
public int UpdateUser(UserInfo ui);
//删除信息
public int deleteUser(int id);
// 批处理添加数据
public int [] addBatchUser(List<UserInfo> list);
然后在接口的实现类中添加方法
//添加信息
@Override
public int AddUser(UserInfo ui) {
//数据库连接对象
Connection conn = DBtest.getConn();
String sql = "insert into emp values(?,?,?,?,?,?,?,?)";
int result = 0;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,ui.getEmpno());
ps.setString(2,ui.getEname());
ps.setString(3,ui.getJob());
ps.setInt(4,ui.getMgr());
ps.setString(5,ui.getHiredate());
ps.setInt(6,ui.getSal());
ps.setInt(7,ui.getComm());
ps.setInt(8,ui.getDeptno());
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//更新数据
@Override
public int UpdateUser(UserInfo ui) {
//数据库连接对象
Connection conn = DBtest.getConn();
String sql = "update emp set ename=?,job=?,mgr=?,hiredate=?,sal=?,comm=?,deptno=? where empno = ?";
int result = 0;
try {
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,ui.getEname());
ps.setString(2,ui.getJob());
ps.setInt(3,ui.getMgr());
ps.setString(4,ui.getHiredate());
ps.setInt(5,ui.getSal());
ps.setInt(6,ui.getComm());
ps.setInt(7,ui.getDeptno());
ps.setInt(8,ui.getEmpno());
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//删除信息
@Override
public int deleteUser(int id) {
int result = 0;
Connection conn = DBtest.getConn();
String sql = "delete from emp Where empno = ?";
try {
PreparedStatement pps = conn.prepareStatement(sql);
pps.setInt(1,id);
result = pps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//批处理
@Override
public int[] addBatchUser(List<UserInfo> list) {
Connection conn = DBtest.getConn();
int [] result = null;
try {
conn.setAutoCommit(false);
String sql = "insert into emp value(?,?,?,?,?,?,?,?)";
//预编译语句
PreparedStatement pps = conn.prepareStatement(sql);
Iterator<UserInfo> iter = list.iterator();
while (iter.hasNext()){
UserInfo ui = iter.next();
pps.setInt(1,ui.getEmpno());
pps.setString(2,ui.getEname());
pps.setString(3,ui.getJob());
pps.setInt(4,ui.getMgr());
pps.setString(5,ui.getHiredate());
pps.setInt(6,ui.getSal());
pps.setInt(7,ui.getComm());
pps.setInt(8,ui.getDeptno());
pps.addBatch();
}
result = pps.executeBatch();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return new int[0];
}