zoukankan      html  css  js  c++  java
  • java jdbc操作数据库通用代码

    1.准备工作

    1》

    新建一个配置文件,名为jdbc.properties将其放入src中

    2》在项目中导入jdbc驱动,注意连接不同的数据库,所用到的驱动是不一样的,这些在网上都能找到

    具体导入jar的方法,请参照http://blog.csdn.net/mazhaojuan/article/details/21403717

    2、代码

      1 import java.io.InputStream;
      2 import java.sql.Connection;
      3 import java.sql.DriverManager;
      4 import java.sql.ResultSet;
      5 import java.sql.SQLException;
      6 import java.sql.Statement;
      7 import java.util.Properties;
      8 
      9 public class Main {
     10     public static void main(String[] args) {
     11         DBUtil dbUtil = new DBUtil();
     12         dbUtil.R("select * from table");
     13     }
     14 }
     15 
     16 class DBUtil{
     17     /**
     18      * 得到数据库连接
     19      * @return
     20      * @throws Exception
     21      */
     22     public Connection getConnection() throws Exception{
     23         //1.创建配置文件并得到对象输入流
     24         InputStream is = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
     25         //2.创建propetities
     26         Properties jdbc = new Properties();
     27         jdbc.load(is);
     28         //3. 通过key-value 的方式得到对应的值
     29         String driver = jdbc.getProperty("driver");
     30         String url = jdbc.getProperty("url");
     31         String user = jdbc.getProperty("user");
     32         String password = jdbc.getProperty("password");
     33         //4.加载运行时类对象
     34         Class.forName(driver);
     35         //5通过DriverManager得到连接
     36         Connection connection = DriverManager.getConnection(url,user,password);
     37         return connection;
     38         
     39     }
     40     /**
     41      * 释放资源的方法
     42      * @param connection
     43      * @param statement      
     44      * @param resultSet
     45      */
     46     public void release(Connection connection,Statement statement,ResultSet resultSet){
     47         try {
     48             if(resultSet!=null){
     49                 resultSet.close();
     50             }
     51          } catch (SQLException e) {
     52             e.printStackTrace();
     53         }
     54          try {
     55             if(statement!=null){
     56                 statement.close();
     57             }
     58           } catch (SQLException e) {
     59             e.printStackTrace();
     60           }
     61          try {
     62             if(connection!=null){
     63                 connection.close();
     64             }
     65         } catch (SQLException e) {
     66             e.printStackTrace();
     67         }
     68         
     69     }
     70     /**
     71      * 查询数据库的方法
     72      * @param sql        字符串,要执行的sql语句  如果其中有变量的话,就用  ‘"+变量+"’
     73      */
     74     public void R(String sql){
     75         Connection connection = null;
     76         Statement statement = null;
     77         ResultSet resultSet = null;
     78         try {
     79             connection = getConnection();
     80             statement = connection.createStatement();
     81             resultSet = statement.executeQuery(sql);
     82             while(resultSet.next()!=false){
     83                 //这里可以执行一些其他的操作
     84                 System.out.println(resultSet.getString(1));
     85             }
     86         } catch (Exception e) {
     87             e.printStackTrace();
     88         }finally {
     89             release(connection, statement, resultSet);
     90         }
     91     }
     92     /**
     93      * 数据库记录增删改的方法
     94      * @param sql        字符串,要执行的sql语句  如果其中有变量的话,就用  ‘"+变量+"’
     95      */
     96     public void CUD(String sql){
     97         Connection connection = null;
     98         Statement statement = null;
     99         int result = 0;
    100         try {
    101             connection = getConnection();
    102             statement = connection.createStatement();
    103             result = statement.executeUpdate(sql);
    104             
    105             //这里可以根据返回结果(影响记录的条数) 进行判断,该语句是否执行成功
    106             System.out.println(result);
    107         } catch (Exception e) {
    108             e.printStackTrace();
    109         }finally {
    110             release(connection, statement, null);
    111         }
    112     }
    113     
    114 }        

    3.预处理,其中上面的连接数据库及释放资源的方法不动

    代码如下:

      1 import java.io.InputStream;
      2 import java.sql.Connection;
      3 import java.sql.DatabaseMetaData;
      4 import java.sql.DriverManager;
      5 import java.sql.PreparedStatement;
      6 import java.sql.ResultSet;
      7 import java.sql.ResultSetMetaData;
      8 import java.sql.SQLException;
      9 import java.sql.Statement;
     10 import java.util.Properties;
     11 
     12 public class Main {
     13     public static void main(String[] args) {
     14        
     15     }
     16 }
     17 
     18 class DBUtil{
     19     /**
     20      * 得到数据库连接
     21      * @return
     22      * @throws Exception
     23      */
     24     public Connection getConnection() throws Exception{
     25         //1.创建配置文件并得到对象输入流
     26         InputStream is = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties.txt");
     27         //2.创建propetities
     28         Properties jdbc = new Properties();
     29         jdbc.load(is);
     30         //3. 通过key-value 的方式得到对应的值
     31         String driver = jdbc.getProperty("driver");
     32         String url = jdbc.getProperty("url");
     33         String user = jdbc.getProperty("user");
     34         String password = jdbc.getProperty("password");
     35         //4.加载运行时类对象
     36         Class.forName(driver);
     37         //5通过DriverManager得到连接
     38         Connection connection = DriverManager.getConnection(url,user,password);
     39         return connection;
     40         
     41     }
     42     /**
     43      * 释放资源的方法
     44      * @param connection
     45      * @param statement      
     46      * @param resultSet
     47      */
     48     public void release(Connection connection,Statement statement,ResultSet resultSet){
     49         try {
     50             if(resultSet!=null){
     51                 resultSet.close();
     52             }
     53         } catch (SQLException e) {
     54             e.printStackTrace();
     55         }
     56         try {
     57              if(statement!=null){
     58                  statement.close();
     59              }
     60         } catch (Exception e) {
     61             // TODO: handle exception
     62         }
     63        try{
     64             if(connection!=null){
     65                 connection.close();
     66             }
     67         } catch (SQLException e) {
     68             e.printStackTrace();
     69         }
     70         
     71     }
     72     /**
     73      * 查询数据库的方法
     74      * @param sql        字符串,要执行的sql语句  如果其中有变量的话,就用  ‘"+变量+"’
     75      */
     76     public void R(String sql, Object ...args){
     77         Connection connection = null;
     78         PreparedStatement preparedStatement = null;
     79         ResultSet resultSet = null;
     80         try {
     81             connection = getConnection();
     82             preparedStatement = connection.prepareStatement(sql);
     83             for (int i = 0; i < args.length; i++) {
     84                 preparedStatement.setObject(i+1, args[i]);
     85             }
     86             resultSet = preparedStatement.executeQuery();
     87             ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
     88             int columnCount = resultSetMetaData.getColumnCount();
     89             while(resultSet.next()!=false){
     90                 //这里可以执行一些其他的操作
     91                 for (int i = 1; i <= columnCount; i++) {
     92                     System.out.println(resultSet.getString(i));
     93                 }
     94             }
     95         } catch (Exception e) {
     96             e.printStackTrace();
     97         }finally {
     98             release(connection, preparedStatement, resultSet);
     99         }
    100     }
    101     /**
    102      * 数据库记录增删改的方法
    103      * @param sql        字符串,要执行的sql语句  如果其中有变量的话,就用  ‘"+变量+"’
    104      */
    105     public void CUD(String sql, Object ...args){
    106         Connection connection = null;
    107         PreparedStatement preparedStatement = null;
    108         int result = 0;
    109         try {
    110             connection = getConnection();
    111             preparedStatement = connection.prepareStatement(sql);
    112             for (int i = 0; i < args.length; i++) {
    113                 preparedStatement.setObject(i+1, args[i]);
    114             }
    115             result = preparedStatement.executeUpdate();
    116             //这里可以根据返回结果(影响记录的条数)进行判断,该语句是否执行成功
    117             System.out.println(result);
    118         } catch (Exception e) {
    119             e.printStackTrace();
    120         }finally {
    121             release(connection, preparedStatement, null);
    122         }
    123     }  
    124     
    125 }

    在预处理代码第87行使用了元数据获取集合中的列的数量  有关数据库 元数据,请参考文档上的相关接口:

    DatabaseMetaData

    ResultSetMetaData

     注:本文为原创,如需转载请注明出处:http://www.cnblogs.com/zhuchenglin/p/7919803.html

  • 相关阅读:
    自己回答自己的问题
    作业5 四则运算 测试与封装 5.1 5.2
    2015430 加法阶段一的封装测试
    20150423 提问2
    Java 泛型中的<? super T>和<? extends T>
    ssh 查看端口占用
    Java 回调
    SpringMVC4+MyBaits3配置
    Selenium 远程执行和监听类
    Intellij idea主题
  • 原文地址:https://www.cnblogs.com/zhuchenglin/p/7919803.html
Copyright © 2011-2022 走看看