JDBC--PrepareStatement对象-程序

本文探讨了在JDBC程序中使用PrepareStatement对象的优势,解释了它如何通过预编译SQL语句提高数据库操作性能。通过这种方式,当多次执行相同的SQL时,数据库可以避免重复编译,直接从缓冲区获取指令,从而提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运行第一个JDBC程序时成功加载到数据库中内容,但程序还有不足之处,具体改进如下:

1.注册驱动

为了避免数据库驱动被重复注册,只需要在程序中加载驱动类即可
Class.forName("com.mysql.jdbc.Driver);
2.释放资源
当数据库资源使用完毕后,一定要释放资源
3.prepareStatement对象
SQL语句的执行时通过Statement对象实现的。Statement对象每次执行SQL语句时,都会对其进行编译。当相同的
SQL语句执行多次时,Statement对象就会是数据库频繁的编译相同的SQL语句,从而降低数据库的访问效率。

Statement提供了一个子类,PrepareStatement,可以对SQL语句进行编译。也就是说相同的SQL语句再次执行时,

数据库只需要使用缓冲区中的数据,不需要对SQL语句重新编译。

JDBC程序如下:

package mysql;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import java.sql.SQLException;
public class E02 {
  public static void main(String args[])throws SQLException {
	 
	  Connection conn=null;
	  PreparedStatement preStmt=null;
	  try{
		/*通过DriverManage连接数据库
		 DriverManager.registerDriver(new com.mysql.jdbc.Driver());*/
	 //加载数据库驱动
	  Class.forName("com.mysql.jdbc.Driver");
	  String url="jdbc:mysql://localhost:3306/chapter01";
	  String username="root";
	  String password=" ";//自己填写
	  //创建数据库与应用程序连接的Connection对象
	   conn=(Connection) DriverManager.getConnection(url,username,password);
	  /*通过Connection对象获取Statement对象
	   Statement stmt=(Statement)conn.createStatement();*/
	  //使用Statement执行SQL语句
	  String sql="INSERT INTO users(name,password,email,birthday)"+"values(?,?,?,?)";
	
	  //操作 ResultSet结果集
	      preStmt=(PreparedStatement)conn.prepareStatement(sql);
		  preStmt.setString(1, "ZL");
		  preStmt.setString(2, "123456");
		  preStmt.setString(3, "ZL@sina.com");
		  preStmt.setString(4, "1993-03-05");
		  preStmt.executeUpdate();
	  }catch(ClassNotFoundException e){
		e.printStackTrace();
	  }finally{   //释放资源
		  if(preStmt !=null){
		  try{
			  preStmt.close();
		  }catch(SQLException e){
			  e.printStackTrace();
		  }
		  preStmt=null;
		  }
		  if(conn !=null){
			  try{
				  conn.close();
			  }catch(SQLException e){
				  e.printStackTrace();
			  }
			  conn=null;
			  }
		  }
		  }
	  }

使用PreparedStatement对象执行sql语句,首先通过Connection对象的PrepareStatement()方法生成PrepareStatement对象,
然后调用PrepareStatement对象的setXXX()方法,给SQL的参数赋值,最后调用executeUpdate()方法执行SQL语句。
运行成功后,会在数据库chapter01的users表中插入一条数据。

结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值