天天看点

PrepareStatement

 PreparedStatement

–Statement只能静态操作SQL语句,如果要想动态操作SQL语句又该如何实现呢?例如:注册会员

–这里可以使用PreparedStatement来动态操作SQL语句

–PreparedStatement通过使用占位符“?”,来预生成SQL语句,从而达到动态操作的功能 • 为占位符“?”赋值

–根据当前SQL的数据类型 调用相应的如下方法

PrepareStatement

import java.sql.Connection;   

import java.sql.PreparedStatement;   

import java.sql.SQLException;   

public class TestPrepareStatement {   

        public staticvoid add(Customer c){   

                Connection conn = new ConnectionUtil().openConnection();   

                String sql = "insert into CustomerTbl(name,email) values(?,?)";   

                try {   

                        PreparedStatement pstmt = conn.prepareStatement(sql);   

                        pstmt.setString(1, c.getName());   

                        pstmt.setString(2, c.getEmail());   

                        pstmt.executeUpdate();   

                } catch (SQLException e) {   

                        e.printStackTrace();   

                }   

        }   

}