標籤:puts set round 根據 ring turn als ssl import
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操作資料庫通用代碼