今天學習的內容是:JDBC http://www.cnblogs.com/centor/p/6142775.html 首先我們把這部分內容仔細閱讀然後複製粘貼到下麵 以mysql為例 工具:eclipse MySQL5.6 MySQL連接驅動:mysql-connector-java-5.1.27. ...
今天學習的內容是:JDBC
http://www.cnblogs.com/centor/p/6142775.html
首先我們把這部分內容仔細閱讀然後複製粘貼到下麵
以mysql為例
工具:eclipse
MySQL5.6
MySQL連接驅動:mysql-connector-java-5.1.27.jar
載入驅動:
1. 在工程目錄中創建lib文件夾,將下載好的JDBC放到該文件夾下,如下圖所示:
2. 右鍵工程名,在java build path中的Libraries分頁中選擇Add JARs...,選擇剛纔添加的JDBC,如下圖:
數據包准備:
在資料庫sqltestdb中創建如下數據表emp:
1 2 3 4 5 6 7 |
CREATE TABLE emp(
empno INT (4) PRIMARY KEY ,
ename VARCHAR (10),
job VARCHAR (9),
hiredate DATE ,
sal FLOAT (7,2)
) ;
|
添加數據:
連接資料庫並讀取數據:
資料庫名稱:sqltestdb
數據包名稱:emp
埠號:3306
用戶名:root
密碼:root
![複製代碼](https://common.cnblogs.com/images/copycode.gif)
1 package sqldemo; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 public class main { 10 11 public static void main(String[] args) { 12 //聲明Connection對象 13 Connection con; 14 //驅動程式名 15 String driver = "com.mysql.jdbc.Driver"; 16 //URL指向要訪問的資料庫名mydata 17 String url = "jdbc:mysql://localhost:3306/sqltestdb"; 18 //MySQL配置時的用戶名 19 String user = "root"; 20 //MySQL配置時的密碼 21 String password = "123456"; 22 //遍歷查詢結果集 23 try { 24 //載入驅動程式 25 Class.forName(driver); 26 //1.getConnection()方法,連接MySQL資料庫!! 27 con = DriverManager.getConnection(url,user,password); 28 if(!con.isClosed()) 29 System.out.println("Succeeded connecting to the Database!"); 30 //2.創建statement類對象,用來執行SQL語句!! 31 Statement statement = con.createStatement(); 32 //要執行的SQL語句 33 String sql = "select * from emp"; 34 //3.ResultSet類,用來存放獲取的結果集!! 35 ResultSet rs = statement.executeQuery(sql); 36 System.out.println("-----------------"); 37 System.out.println("執行結果如下所示:"); 38 System.out.println("-----------------"); 39 System.out.println("姓名" + "\t" + "職稱"); 40 System.out.println("-----------------"); 41 42 String job = null; 43 String id = null; 44 while(rs.next()){ 45 //獲取stuname這列數據 46 job = rs.getString("job"); 47 //獲取stuid這列數據 48 id = rs.getString("ename"); 49 50 //輸出結果 51 System.out.println(id + "\t" + job); 52 } 53 rs.close(); 54 con.close(); 55 } catch(ClassNotFoundException e) { 56 //資料庫驅動類異常處理 57 System.out.println("Sorry,can`t find the Driver!"); 58 e.printStackTrace(); 59 } catch(SQLException e) { 60 //資料庫連接失敗異常處理 61 e.printStackTrace(); 62 }catch (Exception e) { 63 // TODO: handle exception 64 e.printStackTrace(); 65 }finally{ 66 System.out.println("資料庫數據成功獲取!!"); 67 } 68 } 69 70 }
![複製代碼](https://common.cnblogs.com/images/copycode.gif)
運行結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Succeeded connecting to the Database !
-----------------
執行結果如下所示:
-----------------
姓名 職稱
-----------------
李興華 經理
張三 總監
王五 廠長
齊秦 書記
張剛 組長
曹操 財務
李四 總裁
資料庫數據成功獲取!!
|
增加、刪除和修改數據:
增加數據:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
String name;
String id;
PreparedStatement psql;
ResultSet res;
//預處理添加數據,其中有兩個參數--“?”
psql = con.prepareStatement( "insert into emp (empno,ename,job,hiredate,sal) "
+ "values(?,?,?,?,?)" );
psql.setInt( 1 , 3212 ); //設置參數1,創建id為3212的數據
psql.setString( 2 , "王剛" ); //設置參數2,name 為王剛
psql.setString( 3 , "總裁" );
DateFormat dateFormat2 = new SimpleDateFormat( "yyyy-MM-dd" );
Date myDate2 = dateFormat2.parse( "2010-09-13" );
psql.setDate( 4 , new java.sql.Date(myDate2.getTime()));
psql.setFloat( 5 , ( float ) 2000.3 );
psql.executeUpdate(); //執行更新
|
運行結果:
更新數據:
1 2 3 4 5 6 |
PreparedStatement psql;
//預處理更新(修改)數據,將王剛的sal改為5000.0
psql = con.prepareStatement( "update emp set sal = ? where ename = ?" );
psql.setFloat( 1 ,( float ) 5000.0 );
psql.setString( 2 , "王剛" );
psql.executeUpdate();
|
更改結果:
刪除數據:
1 2 3 4 5 6 |
PreparedStatement psql;
//預處理刪除數據
psql = con.prepareStatement( "delete from emp where sal > ?" );
psql.setFloat( 1 , 4500 );
psql.executeUpdate();
psql.close();
|
刪除結果:
------------------------------------------------------------------------------------------------
這個例子可以說很經典了,還在上學的時候,老師講jdbc連接就用的類似的方法(懷念QAQ)
不過在項目中,這些東西通常是配在xml或是properties文件里多一點,就像這樣
----------------------------------------------------------------------------------------------------
接下來我找一個連接池的例子,相當於寫了一個共通類,別的class各種調用這裡的方法,也還算方便
這是我之前做畢業設計那會費了好大勁湊出來的,不知道正不正宗,反正是能跑起來!
1 public class BaseDao { 2 // list連接池 3 static ArrayList<Connection> list = new ArrayList<Connection>(); 4 /** 5 * 從連接池中獲得一個連接 6 */ 7 public synchronized static Connection getConnection() throws Exception{ 8 Connection con = null; 9 // 如果連接池有連接 10 if (list.size() > 0) { 11 return list.remove(0); 12 } 13 // 連接池中沒有連接 14 else { 15 Properties p = new Properties(); 16 //載入配置文件 17 p.load(BaseDao.class.getClassLoader().getResourceAsStream("dao/jdbc.properties")); 18 String driverClass = p.getProperty("jdbc.driverClass"); 19 String jdbcUrl = p.getProperty("jdbc.jdbcUrl"); 20 String username = p.getProperty("jdbc.username"); 21 String password = p.getProperty("jdbc.password"); 22 //載入驅動 23 Class.forName(driverClass); 24 // 和指定的資料庫建立連接 25 for (int i = 0; i < 10; i++) { 26 con = DriverManager.getConnection(jdbcUrl, username,password); 27 list.add(con); 28 } 29 } 30 return list.remove(0); 31 } 32 /** 33 * 關閉結果集 34 * @param rs代表結果集 35 */ 36 public static void close(ResultSet rs) throws Exception{ 37 if (rs != null) 38 rs.close(); 39 } 40 /** 41 * 關閉預處理對象 42 * @param pst代表預處理 43 */ 44 public static void close(PreparedStatement pst) throws Exception{ 45 if (pst != null) 46 pst.close(); 47 } 48 /** 49 * 關閉連接對象 50 * @param con代表連接對象 51 */ 52 public synchronized static void close(Connection con) { 53 if (con != null) 54 list.add(con); 55 } 56 /** 57 * 關閉結果集,預處理,連接等對象 58 * @param rs 結果集 59 * @param ps 預處理 60 * @param con 連接 61 */ 62 public static void close(ResultSet rs, PreparedStatement ps, Connection con) throws Exception{ 63 close(rs); 64 close(ps); 65 close(con); 66 } 67 /** 68 * 根據SQL語句,進行insert,update,delete等操作 69 * @param sql 70 * @param param代表SQL語句裡面的通配符(?)對應的值,一定註意順序 71 * @return 72 */ 73 public boolean updateByParams(String sql, Object param[]) throws Exception{ 74 boolean flag = false; 75 Connection con = getConnection(); 76 PreparedStatement ps = null; 77 ps = con.prepareStatement(sql); 78 //替換參數? 79 if(param != null){ 80 for(int i = 1; i <= param.length; i++){ 81 ps.setObject(i, param[i-1]); 82 } 83 } 84 int n = ps.executeUpdate(); 85 if(n > 0) 86 flag = true; 87 close(null, ps, con); 88 return flag; 89 } 90 /** 91 * 批量進行insert,update,delete等操作 92 * @param sql 93 * @param param 94 * @return 95 */ 96 public boolean BatchUpdateByParams(String sql, Object param[][]) throws Exception{ 97 Connection con = getConnection(); 98 PreparedStatement ps = null; 99 ps = con.prepareStatement(sql); 100 //替換參數? 101 if(param != null){ 102 for(int i = 0; i < param.length; i++){ 103 for(int j = 1; j <= param[i].length; j++){ 104 ps.setObject(j, param[i][j-1]); 105 } 106 ps.addBatch(); 107 } 108 ps.executeBatch(); 109 } 110 close(null, ps, con); 111 return true; 112 } 113 /** 114 * 查詢操作 115 * @param sql 116 * @param param 117 * @return List<Map<String, Object>>,map的key是查詢的列名(小寫)或別名,map的value是每列對應的值 118 */ 119 public static List<Map<String, Object>> select(String sql,Object[] param) throws Exception{ 120 Connection con = getConnection(); 121 PreparedStatement ps = null; 122 ResultSet rs = null; 123 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); 124 ps = con.prepareStatement(sql); 125 //替換參數? 126 if(param != null){ 127 for(int i = 1; i <= param.length; i++){ 128 ps.setObject(i, param[i-1]); 129 } 130 } 131 rs = ps.executeQuery();//執行查詢 132 ResultSetMetaData rm = rs.getMetaData(); 133 //獲得結果集列的總數 134 int count = rm.getColumnCount(); 135 while(rs.next()){ 136 Map<String,Object> map = new HashMap<String, Object>(); 137 for(int i = 1; i <= count; i++){ 138 //key是列名,並且是小寫的;value是根據列名獲得某條記錄對應的值 139 map.put(rm.getColumnName(i).toLowerCase(), rs.getObject(rm.getColumnName(i))); 140 } 141 list.add(map); 142 } 143 close(rs, ps, con); 144 return list; 145 } 146 /** 147 * 獲得一個以時間字元串為標準的ID,固定長度是17位 148 * @return 149 */ 150 public static String getStringID(){ 151 String id=null; 152 Date date=new Date(); 153 SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS"); 154 id=sdf.format(date); 155 return id; 156 } 157 }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
發現孤傲蒼狼大神也發表過關於連接池的隨筆,寫的很容易理解,下麵是傳送門,我已經認真讀一遍了,你呢?
哎,我何時能和他一樣什麼都會。。。。。。o(╥﹏╥)o
https://www.cnblogs.com/xdp-gacl/p/4002804.html
然後!今天工作過程中出現了有關js jsonp的錯誤,因為快下班了就隨便查了下,感覺這部分挺有意思,那麼!明晚就決定寫這個了!
以上就是我今日份的jdbc學習內容,我們下期再見!