package com.cn21.exception;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class JDBC_exception {
/**
* 1:创建时的区别: Statement stm=con.createStatement(); PreparedStatement
* pstm=con.prepareStatement(sql); 执行的时候: stm.execute(sql); pstm.execute();
* 2: pstm一旦绑定了SQL,此pstm就不能执行其他的Sql,即只能执行一条SQL命令。 stm可以执行多条SQL命令。 3:
* 对于执行同构的sql(只有值不同,其他结构都相同),用pstm的执行效率比较的高,对于异构的SQL语句,Statement的执行效率要高。
* 4:当需要外部变量的时候,pstm的执行效率更高.
* 5:
*
*/
public static void main(String[] args) throws ClassNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
//获取jdbc驱动
Class.forName("com.mysql.jdbc.Driver");
try {
conn = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/helloworld", "root", "root");
conn.setAutoCommit(false);//自动提交关闭
ps = (PreparedStatement) conn.prepareStatement("insert into student values(?,?)");
ps.setInt(1, 4);//?从第一个开始匹配,根据具体得类型传值
ps.setString(2, "zhao");
ps.execute();//执行sql语句
conn.commit();//由于前面的提交关闭,所以此处必须手动提交,以持久化到数据库
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps = null;
}
if(conn != null){//判断是否为空,如果不判断,conn获取出现异常时conn = (Connection) DriverManager.getConnection("..."),此处则会出现空指针异常
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
}
}
}
jdbc----preparestatement的简单使用
最新推荐文章于 2023-04-21 10:13:37 发布