zoukankan      html  css  js  c++  java
  • JAVA JDBC prepareStatement 添加数据

    我们使用prepareStatement来操作数据库,可以防止sql注入,并且无需拼接sql语句.

    核心代码:

    String sql = "insert into customers(name,email,birth)values(?,?,?)";
    ps = connection.prepareStatement(sql);
    ps.setString(1,"哪吒");
    ps.setString(2,"nezha@gamail.com");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdf.parse("1000-01-01");
    ps.setDate(3, new java.sql.Date(date.getTime()));
    ps.execute();

    完整代码

    InputStream is = connectTest.class.getClassLoader().getResourceAsStream("jdbcInfo.properties");
            Properties pro = new Properties();
            pro.load(is);
    
            String user = pro.getProperty("user");
            String password = pro.getProperty("password");
            String url = pro.getProperty("url");
            String driverClass = pro.getProperty("driverClass");
            //利用反射
            Connection connection = null;
            PreparedStatement ps = null;
            try {
                Class.forName(driverClass);
                connection = DriverManager.getConnection(url,user,password);
                System.out.println(connection);
    
                String sql = "insert into customers(name,email,birth)values(?,?,?)";
                ps = connection.prepareStatement(sql);
                ps.setString(1,"哪吒");
                ps.setString(2,"nezha@gamail.com");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse("1000-01-01");
                ps.setDate(3, new java.sql.Date(date.getTime()));
                ps.execute();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                if(ps!=null)
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                if(connection!=null)
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
            }
    View Code
  • 相关阅读:
    “非工作总结”之快门—我的镜头见过你
    书摘:日本式管理和依靠自己
    寒冬日,找阳光
    模式自由(Schemafree)和数据存储的非格式化趋势
    心体澄澈,意气和平
    思考些管理的事情
    含沙射影,业镜照胆
    临崖之马,上滩之舟—凡事一定要区别不同情况对待
    [转]HttpContext.Current.Cache 和 HttpRuntime.Cache
    句柄、引用、指针与对象(转)
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/12395673.html
Copyright © 2011-2022 走看看