//【1】类加载器
Class.forName("com.mysql.cj.jdbc.Driver");
//【2】连接数据库获得conn对象
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/studb?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8", "root", "123456");
//【3】创建命令发送器
Statement statement = conn.createStatement();
//【4】执行sql语句,返回结果
int i = statement.executeUpdate("insert into clazz values(null,'政治')");
//【5】处理结果
if(i>0){
System.out.println("操作成功");
}
else{
System.out.println("操作失败");
}
//【6】关闭资源
statement.close();
conn.close();
statement 和 preparestatment 的区别
1.statement
会将输出结果进行拼接
效率高
2 preparestatement 继承的statement接口 预编译
可以用占位符来进行填充,这样可以防止sql注入
用于执行批处理的时候要比statement要效率更高
Connection conn = getConnection();
PreparedStatement pstm = null;
int update=0;
try {
pstm = conn.prepareStatement(sql);
for(int i=0; i<obj.length ; i++){
pstm.setObject(i+1,obj[i]);
}
update = pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeAll(pstm,conn,null);
}
return update;
事务的处理:为了保证安全,比如账户转账,要么都成功,如果没办法全部执行成功,就进行数据回滚
try {
conn.setAutoCommit(false);
pstm= conn.prepareStatement("update acount set sal=sal-200 where id=1");
pstm.executeUpdate();
int x = 1 / 0;
pstm2 = conn.prepareStatement("update acount set sal=sal+200 where id=2");
pstm2.executeUpdate();
conn.commit(); //以上俩条都执行成功了会执行下面的
}catch (Exception e){
conn.rollback(); //如果出现问题数据回滚
e.printStackTrace();
}