jdbc之PreparedStatement

package jdbc;
import java.sql.*;
public class PreparedStatementDemo {
public static void main(String[] args) throws SQLException{
//    在test1中,SQL语句的执行是通过Statement对象实现的。Statement对象每次执行SQL语句时,都会对其进行编译。当相同的SQL语句执行多次时,Statement对象就会使数据库频繁编译相同的SQL语句,从而降低数据库的访问效率
//    为了解决上述问题,Statement提供了一个子类PreparedStatement,PreparedStatement对象可以对SQL语句进行预编译,预编译的信息会存储在PreparedStatement对象中
                PreparedStatement pstmt = null;//创建PreparedStatement对象
                Connection conn = null;
                try {
//                    注册数据库驱动
                    Class.forName("com.mysql.jdbc.Driver");
//                    2.通过DriverManager获取数据库连接
                    String url = "jdbc:mysql://localhost:3306/jdbc?useSSL = false";
                    String username = "root";
                    String password = "root";
                    conn = DriverManager.getConnection(url, username, password);
//                    3.使用Statement执行SQL语句
                    String sql = "insert into users(name,password,email,birthday)"+"values(?,?,?,?)";
//                    4.创建执行SQL语句的prepareStatement对象
                    pstmt = conn.prepareStatement(sql);
//                    5.为SQL与语句中参数赋值,即value的值name,password,email,birthday,因为id有auto_increse所以可以不写
                    pstmt.setString(1, "ZL");
                    pstmt.setString(2, "123456");
                    pstmt.setString(3, "ZL@sina.com");
                    pstmt.setString(4, "1789-12-23");
//                    6.执行SQL
                    pstmt.executeUpdate();
                    
                }catch(Exception e) {
                    e.printStackTrace();
                }finally {
//                    7.回收数据库资源
                    if(pstmt != null) {
                        try {
                            pstmt.close();
                        }catch(SQLException e) {
                            e.printStackTrace();
                        }
                        pstmt = null;
                    }
                    if(conn != null) {
                        try {
                            conn.close();
                        }catch(SQLException e) {
                            e.printStackTrace();
                        }
                        conn = null;
                    }
                }


    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值