Java連線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 |
TABLE emp(
|
新增資料:
連線資料庫並讀取資料:
資料庫名稱:sqltestdb
資料包名稱:emp
埠號:3306
使用者名稱:root
密碼:root
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 }
執行結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
增加、刪除和修改資料:
增加資料:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
執行結果:
更新資料:
1 2 3 4 5 6 |
|
更改結果:
刪除資料:
1 2 3 4 5 6 |
|
刪除結果: