原生JDBC开发

原生JDBC的开发

  1. 初始化驱动
    Class.forName("com.mysql.jdbc,Driver")
  2. 获取连接
    //使用DriverManager类获取连接
    Connection conn = DriverManager.getConnection(url,username,password)
  3. 获取SQL语句执行对象
    String sql = "sql语句"
    PreparedStatement pt = new PreparedStatement(sql)
  4. 执行sql语句
    增删改:(int)pt.excuteUpdate()
    查: (ResultSet)pt.excuteQuery()
  5. 关闭连接
    先创建的后关闭

PreparedStatement 的优点
1、使用参数设置
String sql = "insert into hero values(null,?,?,?)";
pt.setString( 1 , "value1")
2、性能好
3、防止SQL注入

execute与executeUpdate的区别
不同1:
execute可以执行查询语句
然后通过getResultSet,把结果集取出来
executeUpdate不能执行查询语句
不同2:
execute返回boolean类型,true表示执行的是查询语句,false表示执行的是insert,delete,update等等
executeUpdate返回的是int,表示有多少条数据受到了影响

JDBC工具类

  1. 编写配置文件(数据库用户名,密码等)

     1、编写jdbc.properties
         driver=com.mysql.jdbc.Driver
         url=jdbc:mysql://localhost:3306/database?characterEncoding=utf8
         username=root
         password:1234
    
  2. 创建JDBCUtils类

    1、初始化实例域
        private static String url ;  
    
        private static String userName ;  
    
        private static String password;  
           
        private static String driver; 
        
    2、使用静态方法获得数据库配置和注册驱动
    static {
        InputStream inStream = JDBCUtil.class.getResourceAsStream("/jdbc.properties");  
        Properties prop = new Properties();  
        prop.load(inStream);  
        USERNAME = prop.getProperty("jdbc.username");  
        PASSWORD = prop.getProperty("jdbc.password");  
        DRIVER= prop.getProperty("jdbc.driver");  
        URL = prop.getProperty("jdbc.url");
        Class.forName(driver); 
        
    }
    
    3、 获得连接
        public static Connection getConnection() throws SQLException {  
            Connection conn = null;  
            conn = DriverManager.getConnection(url, userName, password);  
            return conn;  
        }  
    

你可能感兴趣的:(原生JDBC开发)