public class JDBC2 {
public static void main(String[] args) {
Connection cn = null;
PreparedStatement psm = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "piao";
try {
//mysql对于接口实现的驱动进行加载
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection(url, user, password);
//设置事务提交
cn.setAutoCommit(false);
//PreparedStatement可预编译,效率更高,并且有防止sql注入等优势于Statement
psm = cn.prepareStatement("INSERT INTO student(name, password) VALUES(?,?);");
psm.setString(1, "xiaoqiang");
psm.setString(2, "123");
//添加到批处理中
psm.addBatch();
psm.setString(1, "xiaoruo");
psm.setString(2, "123");
//添加到批处理中
psm.addBatch();
//执行批处理
psm.executeBatch();
cn.commit();
//查询,如果把错误注掉便能查到刚插入的数据
rs = psm.executeQuery("SELECT * FROM student");
//根据数据库显示行返回,如果到最后的空行返回false
while(rs.next()){
//根据列取
System.out.println("name " + rs.getString(2) + "password" + rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
try {
cn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally{
//关闭资源
if (psm != null){
try {
psm.close();
} catch (SQLException e) {
e.printStackTrace();
}
psm = null;
}
if (cn != null){
try {
cn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cn = null;
}
}
}
}
JDBC 复习笔记2
最新推荐文章于 2022-02-09 14:47:40 发布