jdbc总结

本文详细介绍Java环境下数据库操作流程,包括连接数据库、执行SQL语句、处理结果等关键步骤,并探讨了SQL注入防护、大文本读写、事务处理及连接池创建等高级主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.    连接数据库的步骤:

1)       注册驱动

2)       建立连接

3)       创建语句

4)       执行语句

5)       处理结果

6)       释放资源(注意关闭的顺序)

实例//1.注册驱动

      

  1.  DriverManager.registerDriver(newcom.mysql.jdbc.Driver());  
  2.         
  3.        System.setProperty("jdbc.drivers""com.mysql.jdbc.Driver");  
  4.         
  5.         Class.forName("com.mysql.jdbc.Driver");//推荐方式  
  6.           
  7.        //2.建立连接  
  8.          
  9.         String url = "jdbc:mysql:localhost:3306/jdbc";  
  10.         String user = "root";  
  11.         String password = "mysql";  
  12. Connection conn = DriverManager.getConnection(url,user,password);  
  13.         
  14.        //3.创建语句  
  15.        Statement st = conn.createStatement();  
  16.         
  17.        //4.执行语句  
  18.        ResultSet rs = st.executeQuery("select * from user");  
  19.        //5.处理结果  
  20.        while(rs.next()){//按行来遍历  
  21. System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t" +rs.getObject(3) + "\t" + rs.getObject(4));  
  22.        }  
  23.        //6.释放资源(注意关闭的顺序)  
  24.        rs.close();  
  25.        st.close();  
  26.        conn.close();  

2.    注意在jdbc中的sql注入问题,解决的办法是使用PreparedStatement :PreparedStatement ps = null;// 利用PreparedStatement而不用Statement是因为PreparedStatement能够对输入的内容进行过滤,除去sql的关键字,防止此问题。

3.    数据库中对大文本的写入和读取:clob类的处理

  1. public class ClobTest {  
  2.    
  3.     /** 
  4.      * @param args 
  5.      * @throws Exception 
  6.      */  
  7.     public static void main(String[] args) throws Exception {  
  8.        //create();  
  9.         read();  
  10.     }  
  11.      //数据库的读取操作  
  12.     static void read() throws SQLException, Exception {  
  13.        Connection conn = null;  
  14.        Statement st = null;  
  15.        ResultSet rs = null;  
  16.        try {  
  17.            conn = JdbcUtils.getConnection();  
  18.            // 3.创建语句  
  19.            st = conn.createStatement();  
  20.            // 4.执行语句  
  21.            rs = st.executeQuery("select big_text from clob_test");  
  22.            // 5.处理结果  
  23.            while (rs.next()) {// 按行来遍历  
  24.               Reader reader = rs.getCharacterStream(1);  
  25.               Filefile = newFile("CRUD_bak.java");  
  26.               Writerwriter = new BufferedWriter(new FileWriter(file));  
  27.               char[] buff = new char[1024];  
  28.               for(int i = 0; (i = reader.read(buff))>0;){  
  29.                   writer.write(buff,0, i);  
  30.               }  
  31.               writer.close();  
  32.               reader.close();  
  33.                
  34.            }  
  35.        } finally {  
  36.            JdbcUtils.free(rs, st, conn);  
  37.        }  
  38.     }  
  39.      
  40.     //数据库的创建操作  
  41.     static void create() throws SQLException, IOException {  
  42.        Connection conn = null;  
  43.        PreparedStatement ps = null;  
  44.        ResultSet rs = null;  
  45.        try {  
  46.            conn = JdbcUtils.getConnection();  
  47.    
  48.            // 3.创建语句  
  49.            String sql = "insertinto clob_test(big_text) values(?)";  
  50.            ps = conn.prepareStatement(sql);  
  51.            File file = new File("src/com/lcq/jdbc/CRUD.java");  
  52.            Reader reader = newBufferedReader(newFileReader(file));  
  53.            //传递大块的文本文档  
  54.            ps.setCharacterStream(1,reader, file.length());  
  55.            int i = ps.executeUpdate();  
  56.            reader.close();  
  57.            System.out.println("i = " + i);  
  58.             
  59.        } finally {  
  60.            JdbcUtils.free(rs, ps, conn);  
  61.        }  
  62.     }  
  63. }  


4.    问题blob类型读取二进制文件

数据库编译时异常的处理,编写自己的异常类

  1. package com.lcq.jdbc.impl;  
  2.    
  3. public class DaoException extends RuntimeException {  
  4.    
  5.     /** 
  6.      * 
  7.      */  
  8.     private static final long serialVersionUID = 1L;  
  9.    
  10.     public DaoException() {  
  11.        // TODO Auto-generatedconstructor stub  
  12.     }  
  13.    
  14.     public DaoException(String message) {  
  15.        super(message);  
  16.        // TODO Auto-generatedconstructor stub  
  17.     }  
  18.    
  19.     public DaoException(Throwablecause) {  
  20.        super(cause);  
  21.        // TODO Auto-generatedconstructor stub  
  22.     }  
  23.    
  24.     public DaoException(String message, Throwable cause) {  
  25.        super(message, cause);  
  26.        // TODO Auto-generatedconstructor stub  
  27.     }  
  28.    
  29. }  
  30. 在使用时  
  31. catch(SQLException e){  
  32.            //异常的处理,转化为运行时异常  
  33.            throw new DaoException(e.getMessage(),e);  
  34.     }  


在sql中SQLException是编译时异常,所以要抛出,但是如果只是向上抛出的话,会导致业务层和数据访问层的关系复杂,后期维护不便;因此最好的解决方法是在数据访问层中将异常catch住,编写异常类进行处理,在运行时如果上层能够处理就处理。从而使业务层和数据访问层耦合度减少。

5.    一个类的实例化的过程中首先执行的是静态代码块,然后是构造函数。

6.     

事务的处理问题:

  1. /** 
  2.  * 事务处理范例 
  3.  * 从账户1转账到账户2十元 
  4.  * 
  5.  */  
  6. static void test() throws SQLException {  
  7.        Connection conn = null;  
  8.        Statement st = null;  
  9.        ResultSet rs = null;  
  10.        Savepoint sp = null;  
  11.        try {  
  12.            conn = JdbcUtils.getConnection();  
  13.            // 3.创建语句  
  14.            Conn.setAutoCommit(false);//设置自动提交无效  
  15.            st = conn.createStatement();  
  16.            // 4.执行语句  
  17.            String sql = "updateuser set money=money-10 where id=1";  
  18.           st.executeUpdate(sql);  
  19.            //设置回滚点  
  20.            sp =conn.setSavepoint();  
  21.            sql = "update userset money=money+10 where id=3";  
  22.           st.executeUpdate(sql);  
  23.            sql = "selectmoney from user where id=2";  
  24.            rs = st.executeQuery(sql);  
  25.            float money = 0.0f;  
  26.             
  27.            // 5.处理结果  
  28.            if (rs.next()) {// 按行来遍历  
  29.               money = rs.getFloat("money");  
  30.            }  
  31.            if(money > 300){  
  32.               throw new RuntimeException("已经达到最大值!");  
  33.                
  34.            }  
  35.            sql = "update userset money=money+10 where id=2";  
  36.            st.executeUpdate(sql);  
  37.            conn.commit();  
  38.               
  39.        } catch(RuntimeException e){  
  40.            if(conn != null && sp != null)  
  41.               //回滚到设置的点  
  42.               conn.rollback(sp);  
  43.            //递交,使以上操作有效  
  44.                conn.commit();  
  45.               throw e;  
  46.        }catch(SQLException e){  
  47.            if(conn != null)  
  48.               conn.rollback();  
  49.               throwe;  
  50.        }finally {  
  51.            JdbcUtils.free(rs, st, conn);  
  52.        }  
  53.     }  


7.    跨越多个数据源的事务(JTA)实现分布式的数据处理,事务处理步骤:

1)       打开事务

2)       提交事务

3)       回滚事务

8.    在数据库中编写组件(函数),通过ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);//能够得到数据库中的组件。这样通过组件可以在用户向数据库中添加数据时,在返回时可以用组件对结果进行标识,说明数据已经在数据库中得到更新。

9.    批处理,对sql语句的打包。

10.  

根据用户的查询需求进行查询,并将结果封装为Map返回

  1. public classResultSetMetaDataTest {  
  2.    
  3.     /** 
  4.      * @param args 
  5.      * @throws SQLException 
  6.      */  
  7.     public static void main(String[] args) throws SQLException {  
  8.        List<Map<String, Object>> datas = read("select * from user");  
  9.        System.out.println(datas);  
  10.     }  
  11.     static List<Map<String, Object>> read(String sql) throws SQLException {  
  12.        Connection conn = null;  
  13.        PreparedStatement ps = null;  
  14.        ResultSet rs = null;  
  15.        try {  
  16.            conn = JdbcUtils.getConnection();  
  17.         
  18.            ps = conn.prepareStatement(sql);  
  19.             
  20.            rs = ps.executeQuery();  
  21.            ResultSetMetaDatarsmd = rs.getMetaData();  
  22.            //得到结果集的列数  
  23.            intcount = rsmd.getColumnCount();  
  24.            String[] colNames = new String[count];  
  25.            for(int i = 1; i < colNames.length;i++){  
  26.               colNames[i-1] = rsmd.getColumnName(i);  
  27.            }  
  28.            List<Map<String, Object>> datas = newArrayList<Map<String, Object>>();  
  29.            // 5.处理结果  
  30.            while (rs.next()) {// 按行来遍历,将每一行添加到map中,list中最后存放的是表  
  31.               Map<String,Object> data = new HashMap<String, Object>();  
  32.               for(inti = 1;i<= colNames.length;i++){  
  33.                   data.put(colNames[i-1],rs.getObject(i));  
  34.               }  
  35.               datas.add(data);  
  36.            }  
  37.            return datas;  
  38.        } finally {  
  39.            JdbcUtils.free(rs, ps, conn);  
  40.        }  
  41.     }  
  42.    
  43. }  

11. 对象与关系的映射(利用反射)

  1. public class ORMTest {  
  2.    
  3.     /** 
  4.      * @param args 
  5.      * @throwsInvocationTargetException 
  6.      * @throwsIllegalAccessException 
  7.      * @throws SQLException 
  8.      * @throwsIllegalArgumentException 
  9.      * @throws InstantiationException 
  10.      */  
  11.     public static void main(String[] args) throws IllegalArgumentException,  
  12.            SQLException, IllegalAccessException,InvocationTargetException,  
  13.            InstantiationException {  
  14.    
  15.        User user = (User) getObject(  
  16.               "select idas Id ,name as Name, birthday as Birthday,money as Money from user whereid=2",  
  17.               User.class);  
  18.        System.out.println(user);  
  19.     }  
  20.    
  21.     static ObjectgetObject(String sql, Class clazz) throws SQLException,  
  22.            IllegalArgumentException, IllegalAccessException,  
  23.            InvocationTargetException, InstantiationException {  
  24.        Connection conn = null;  
  25.        PreparedStatement ps = null;  
  26.        ResultSet rs = null;  
  27.        try {  
  28.            conn = JdbcUtils.getConnection();  
  29.    
  30.            ps = conn.prepareStatement(sql);  
  31.    
  32.            rs = ps.executeQuery();  
  33.            ResultSetMetaData rsmd = rs.getMetaData();  
  34.            // 得到结果集的列数  
  35.            int count = rsmd.getColumnCount();  
  36.            String[] colNames = new String[count];  
  37.            for (int i = 1; i <= colNames.length; i++) {  
  38.               colNames[i - 1] = rsmd.getColumnLabel(i);  
  39.            }  
  40.    
  41.            Object object = null;  
  42.            Method[] ms = clazz.getMethods();  
  43.    
  44.            // 5.处理结果  
  45.            if (rs.next()) {// 按行来遍历,将每一行添加到map中,list中最后存放的是表  
  46.                object = clazz.newInstance();  
  47.               for (int i = 0; i < colNames.length; i++) {  
  48.                   String colName = colNames[i];  
  49.                   String methodName = "set" + colName;  
  50.                   // System.out.println(methodName);  
  51.                   for (Method m : ms) {  
  52.                      if (methodName.equals(m.getName())) {  
  53.                          m.invoke(object, rs.getObject(colName));  
  54.                      }  
  55.                   }  
  56.               }  
  57.            }  
  58.            return object;  
  59.        } finally {  
  60.            JdbcUtils.free(rs, ps, conn);  
  61.        }  
  62.     }  
  63. }  


12. 创建数据库连接池,先创建多个连接,将连接一次放在List的尾部,用的时候从List的头部取出连接,使用连接;用完释放连接的时候是将连接返回到连接池的尾部,供后边的用户使用。达到连接重复使用的目地。

  1. /** 
  2.  * 
  3.  * 创建数据库连接池 
  4.  */  
  5. import java.sql.Connection;  
  6. import java.sql.DriverManager;  
  7. import java.sql.SQLException;  
  8. import java.util.LinkedList;  
  9.    
  10. public class MyDataSource {  
  11.      
  12.     private static String url = "jdbc:mysql://localhost:3306/jdbc";  
  13.     private static String user = "root";  
  14.     private static String password = "mysql";  
  15.      
  16.      
  17.     private LinkedList<Connection>connectionsPoll = new LinkedList<Connection>();  
  18.     public MyDataSource(){  
  19.        for(int i = 0; i<5;i++){  
  20.            try {  
  21.               this.connectionsPoll.addLast(this.createConnection());  
  22.            } catch (SQLException e) {  
  23.                throw newExceptionInInitializerError(e);  
  24.            }  
  25.        }  
  26.     }  
  27.     public Connection getConnection(){  
  28.        return this.connectionsPoll.removeFirst();  
  29.     }  
  30.     private Connection createConnection() throws SQLException{  
  31.        return DriverManager.getConnection(url, user, password);  
  32.     }  
  33.     public void free(Connection conn){  
  34.        this.connectionsPoll.addLast(conn);  
  35.     }  
  36.    
  37. }  


13. 对创建连接的优化,利用dbcp作为数据源,从数据源中取出连接。编写自己的数据源。对代码的优化是从“变与不变”入手的。

14. 通过模板模式对增删改查进行优化,利用抽象和继承实现。

15. 利用工厂模式和sping对数据库的封装进行最终版本的实现。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值