1. 程式人生 > >java jdbc操作數據庫通用代碼

java jdbc操作數據庫通用代碼

com 找到 數據庫 url res sdn 數據 table pre

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.txt");
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 if(statement!=null){ 52 statement.close(); 53 } 54 if(connection!=null){ 55 connection.close(); 56 } 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 } 60 61 } 62 /** 63 * 查詢數據庫的方法 64 * @param sql 字符串,要執行的sql語句 如果其中有變量的話,就用 ‘"+變量+"’ 65 */ 66 public void R(String sql){ 67 Connection connection = null; 68 Statement statement = null; 69 ResultSet resultSet = null; 70 try { 71 connection = getConnection(); 72 statement = connection.createStatement(); 73 resultSet = statement.executeQuery(sql); 74 while(resultSet.next()!=false){ 75 //這裏可以執行一些其他的操作 76 System.out.println(resultSet.getString(1)); 77 } 78 } catch (Exception e) { 79 e.printStackTrace(); 80 }finally { 81 release(connection, statement, resultSet); 82 } 83 } 84 /** 85 * 數據庫記錄增刪改的方法 86 * @param sql 字符串,要執行的sql語句 如果其中有變量的話,就用 ‘"+變量+"’ 87 */ 88 public void CUD(String sql){ 89 Connection connection = null; 90 Statement statement = null; 91 ResultSet resultSet = null; 92 try { 93 connection = getConnection(); 94 statement = connection.createStatement(); 95 resultSet = statement.executeQuery(sql); 96 97 //這裏可以根據返回結果進行判斷,該語句是否執行成功 98 System.out.println(resultSet); 99 } catch (Exception e) { 100 e.printStackTrace(); 101 }finally { 102 release(connection, statement, resultSet); 103 } 104 } 105 106 }

java jdbc操作數據庫通用代碼