java JDBC-PraparedStatement接口操做数据库

PreparedStatement:占位符、预编译、传参、执行、关闭链接
关闭两个链接mysql

public class Demo3 {

public static void main(String[] args) {
    PreparedStatement ps=null;
    Connection conn=null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","dyl123");

        //占位符代替参数
        String sql="insert into t_user (username,pwd) values(?,?)"; //能够防止sql注入
        PreparedStatement ps=conn.prepareStatement(sql);
        //赋值,参数索引从1开始
        ps.setString(1, "我");
        ps.setString(2, "123456");
        //适合多种类型的传入参数
        ps.setObject(1, "你");
        ps.setObject(2, "23456");
        ps.execute(); //返回是否有结果集,便是否成功运行

        //执行insert/update/delete等语句时使用
        System.out.println(ps.executeUpdate()); //ps.executeUpdate(),返回更新和影响了多少条记录
        ps.executeQuery();  //执行select语句时选用,返回ResultSet结果集
    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        try {
            if(null!=conn)
            {
                ps.close();
            }
        } 
        try {
            if(null!=conn)
            {
                conn.close();
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }

}

}
}
相关文章
相关标签/搜索