Java 操作MySQL


      從2011年10月之后就沒有用過JAVA了,真是汗顏啊!

      從2012年5月之后就沒有寫過程序了,真是汗顏!

  今天要做ETL操作,自然第一下就想起了我熟悉的Java。打開eclispe就完全不知道怎么下手了。然后,自己用最簡單的例子回憶了一遍Java操作mysql5.0。操作過程基本熟悉之后,我又想起了一個通用的操作代碼,所幸在百度文庫上面找到了。原作者不詳,我只是將源代碼貼在下面。

 1 package dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 
 8 public class BaseDao {
 9     public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
10     public static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
11     public static final String USERNAME = "ma";
12     public static final String PASSWORD = "malei";
13     
14     Connection connection = null;
15     PreparedStatement preparedStatement = null;
16     ResultSet resultSet = null;
17     
18     public Connection getConnection() throws Exception {
19         Class.forName(DRIVER);
20         connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
21         return connection;
22     }
23     
24     public ResultSet executeQuery(String sql) throws Exception {
25         connection = this.getConnection();
26         preparedStatement = connection.prepareStatement(sql);
27         resultSet = preparedStatement.executeQuery();
28         return resultSet;
29         
30     }
31     
32     public int executeUpdate(String sql,Object[] obj) throws Exception {
33         connection = this.getConnection();
34         preparedStatement = connection.prepareStatement(sql);
35         for(int i =0;i<obj.length;i++){
36             preparedStatement.setObject(i+1, obj[i]);
37         }
38         return preparedStatement.executeUpdate();
39     }
40     
41     public void closeAll() throws Exception {
42         if(null != resultSet){
43             resultSet.close();
44         }
45         if(null != preparedStatement){
46             preparedStatement.close();
47         }
48         if(null != connection){
49             connection.close();
50         }
51     }
52 }

這是我很早之前初學Java時就見過的模版,很優雅。同時也兼顧了性能PreparedStatement和安全性(防SQL注入)兩方面。對於比較簡單的數據庫操作基本滿足要求。

      學習既是訓練思維和與遺忘作斗爭的過程。但是,我相信忘得快,撿起來會更快!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM