JavaJDBC【三、增删改查】
获取数据库连接后,可进行增删改查操作
-
语句生成:
Statement s = con.createStatement(sql); //生成语句
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql); //预准备,可以填充参数
ps.setXXX(n,value); //可以通过set来填充参数值,位置,值 -
参数查询:
s.executeUpdate(); //执行非查询操作,增删改
s.executeQuery(); //执行查询
Demo:
public class JDBCDAO {
public static int addJDBC(JDBCModel m) throws SQLException {
Connection c = DBUtil.GetConnection();
// current_time() mysql内置函数,当前时间
String sql = "insert jdbc (id,name,createtime) "
+ "values(?,?,current_time())";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ps.setLong(1, 0);// 主键自增
ps.setString(2, m.name);
int re = 0;
try {
// 此处若使用execute,会返回false,但插入成功
// false代表第一个执行结果的返回值不是resultset
re = ps.executeUpdate();
System.out.println(re);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return re;
}
public static int deleteJDBC(int i) throws SQLException {
Connection c = DBUtil.GetConnection();
String sql = "delete from jdbc where id=?";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ps.setLong(1, i);
int re = 0;
try {
// 此处若使用execute,会返回false,但插入成功
// false代表第一个执行结果的返回值不是resultset
re = ps.executeUpdate();
System.out.println(re);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return re;
}
public static int updateJDBC(JDBCModel m) throws SQLException {
Connection c = DBUtil.GetConnection();
String sql = "update jdbc set name=? where id=?";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ps.setString(1, m.name);
ps.setLong(2, m.id);
int re = 0;
try {
re = ps.executeUpdate();
System.out.println(re);
} catch (SQLException e) {
e.printStackTrace();
}
return re;
}
public static List<JDBCModel> queryJDBC() throws SQLException {
List<JDBCModel> ml = new ArrayList<JDBCModel>();
Connection c = DBUtil.GetConnection();
String sql = "select * from jdbc ";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ResultSet re = null;
try {
re = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
if (re != null) {
while (re.next()) {
JDBCModel m = new JDBCModel();
m.setId(re.getInt("id"));
m.setName(re.getString("name"));
m.setCreatetime(re.getDate("createtime"));
ml.add(m);
}
}
return ml;
}
}