1. 程式人生 > >MySQL JDBC簡單使用

MySQL JDBC簡單使用

首先需要去MySQL官網下載MySQL JDBC驅動

匯入jar包

 1 String driver = "com.mysql.jdbc.Driver";
 2 String url = "jdbc:mysql://localhost:3306/yourTable";
 3 String username = "root";
 4 String password = "";
 5 Connection connection = null;
 6 try {
 7     Class.forName(driver);  // ClassLoader載入對應驅動
 8     connection = DriverManager.getConnection(url, username, password);
9 } catch (ClassNotFoundException e) { 10 e.printStackTrace(); 11 } catch (SQLException e) { 12 e.printStackTrace(); 13 } 14 /** 15 * 建立表 16 */ 17 String sql = "create table nihao(name varchar(10) primary key, password varchar(10), nowtime date, age int)"; 18 PreparedStatement ps = null
; 19 try { 20 ps = connection.prepareStatement(sql); 21 ps.executeUpdate(); 22 ps.close(); 23 } catch (SQLException e) { 24 e.printStackTrace(); 25 } 26 /** 27 * 插入資料 28 */ 29 sql = "insert into nihao(name, password, nowtime, age) values (?, ?, ?, ?)"; 30 try { 31 ps = connection.prepareStatement(sql);
32 ps.setString(1, "root"); 33 ps.setString(2, "sqdw"); 34 ps.setDate(3, new java.sql.Date(new Date().getTime())); 35 ps.setInt(4, 19); 36 int i = ps.executeUpdate(); 37 System.out.println(i); 38 ps.close(); 39 } catch (SQLException e) { 40 e.printStackTrace(); 41 } 42 /** 43 * 查詢資料 44 */ 45 sql = "select name, password, nowtime, age from nihao"; 46 try { 47 ps = connection.prepareStatement(sql); 48 ResultSet rs = ps.executeQuery(); 49 while (rs.next()) 50 System.out.print("姓名是: " + rs.getString("name") + ", 密碼是:" + rs.getString("password") + 51 ". 日期是: " + rs.getDate("nowtime") + ", 年齡是:" + rs.getInt("age")); 52 ps.close(); 53 } catch (SQLException e) { 54 e.printStackTrace(); 55 } 56 try { 57 connection.close(); 58 } catch (SQLException e) { 59 e.printStackTrace(); 60 }

刪除也用executeUpdate()即可。