zoukankan      html  css  js  c++  java
  • PreparedStatement实现通用的增删改操作

    PreparedStatement实现通用的增删改操作

    public void testCommonUpdate() throws Exception {
        String sql="update customers set name=? where id=?";
        update(sql,"wtf",19);
    }
    public void update(String sql,Object ...args) throws Exception{
        Connection conn=JDBCUtils.getConnection();
    
        PreparedStatement ps = conn.prepareStatement(sql);
    
        for(int i=0;i<args.length;i++){
            ps.setObject(i+1,args[i]);
        }
        ps.execute();
        JDBCUtils.closeResource(conn,ps);
    }
    
    public class JDBCUtils {
        public static Connection getConnection() throws Exception{
            InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
    
            Properties pros=new Properties();
            pros.load(is);
    
            String user=pros.getProperty("user");
            String password=pros.getProperty("password");
            String url=pros.getProperty("url");
            String driverClass=pros.getProperty("driverClass");
    
            Class.forName(driverClass);
    
            Connection conn= DriverManager.getConnection(url,user,password);
            return conn;
        }
        public static void closeResource(Connection conn,Statement ps){
            try{
                if(ps!=null)
                    ps.close();
            } catch (SQLException e){
                e.printStackTrace();
            }
            try{
                if(conn!=null)
                    conn.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
    
        }
    }
    
  • 相关阅读:
    javascript 字符串截取
    HTML5 转
    Javascript try catch finally
    C#之json字符串转xml字符串
    AspNetCore Json序列化设置
    类加载(对象创建)顺序
    线性表,线性表和链表的区别
    Implement int sqrt(int x).
    Add Binary
    Roman to Integer(将罗马数字转成整数)
  • 原文地址:https://www.cnblogs.com/fate-/p/14917749.html
Copyright © 2011-2022 走看看