JAVA数据库JDBC操作基本步骤和防注入

一、基本步骤

注:组成包:java.sql.*;javax.sql.*;这两个包都包含在了JDK中。

1、把数据库的驱动加入到classpath中
2、开发步骤:
* 1、注册驱动
* 2、获取与数据库的链接
* 3、得到代表SQL语句的对象
* 4、执行语句
* 5、如果执行的是查询语句,就会有结果集,处理
* 6、释放占用的资源

二、封装工具类JdbcUtils

public class JdbcUtil {
    private static String driverClass;
    private static String url ;
    private static String user;
    private static String password;

    static{
        InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties p = new Properties();
        try {
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driverClass= p.getProperty("driverClass");
        url = p.getProperty("url");
        user = p.getProperty("user");
        password = p.getProperty("password");

        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到数据库连接
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception{
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放资源
     * @param rs
     * @param st
     * @param con
     */
    public static void release(ResultSet rs,Statement st,Connection conn){
         if(rs!=null){
              try{
                  rs.close();
              }catch(Exception ex){
                  throw new RuntimeException(ex);
              }
          }
          if(st!=null){
              try{
                  st.close();
              }catch(Exception ex){
                  throw new RuntimeException(ex);
              }
          }
          if(conn!=null){
              try{
                  conn.close();
              }catch(Exception ex){
                  throw new RuntimeException(ex);
              }
          }
    }
}

三、防注入(JDBC中的PreparedStatement)

public void saveData(User user) {
        Connection connection = null;
        PreparedStatement stmt = null;
        try {
            conn = JdbcUtils.getConnection();
            stmt = connection.prepareStatement("insert into user (username,password,email,birthday) values (?,?,?,?)");
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getEmail());
            stmt.setString(4, new Data()user.getBirthday().getTime());
            stmt.executeUpdate();

        } catch (Exception e) {
            throw new RuntimeException()
        } finally {
                JdbcUtils.release(null,stmt,conn);
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值