JDBC--PrepareStatement对象-程序
来源:互联网 发布:c语言选择题及答案 编辑:程序博客网 时间:2024/06/02 05:50
运行第一个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表中插入一条数据。
结果
阅读全文
0 0
- JDBC--PrepareStatement对象-程序
- JDBC中的语句对象 statement prepareStatement CallableStatement
- jdbc---------prepareStatement
- JDBC-PrepareStatement批处理
- JDBC的PrepareStatement
- JDBC连接数据库 prepareStatement
- jdbc prepareStatement的运用
- JDBC常用接口PrepareStatement
- JDBC--PrepareStatement 接口
- JDBC PrepareStatement 和 Statement
- jdbc prepareStatement 操作
- JDBC——preparestatement
- jdbc核心之PrepareStatement
- jdbc Statement和PrepareStatement操作
- jdbc----preparestatement的简单使用
- jdbc大量插入数据(prepareStatement)
- JDBC中PrepareStatement与Statement的区别
- JDBC Statement 和 PrepareStatement的用法
- 以太网数据包TCP、IP、ICMP、UDP、ARP协议头结构详解
- XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks
- 复习
- NodeJs——Express、Routes使用【二】
- msql知识点整理
- JDBC--PrepareStatement对象-程序
- hdu1020Encoding
- 精确计算代码执行时间
- XML与JSON比较,并用AJAX传输XML/JSON数据
- Java集合---LinkedList源码解析
- myeclipse快捷键大全
- Leetcode 396 Rotate Function
- 【Shell】用tar分卷打包压缩
- 全脑思维下的项目管理能力提升