標籤:
1 import java.sql.*; 2 3 public class MysqlTest { 4 public static void main(String[] args) { 5 // 驅動程式名 6 String driver = "org.gjt.mm.mysql.Driver"; 7 // URL指向要訪問的資料庫名world 8 // String url = "jdbc:mysql://127.0.0.1:3306/xh"; 9 String url = "jdbc:mysql://localhost/xh";10 // MySQL配置時的使用者名稱11 String user = "xiaohengdada";12 // MySQL配置時的密碼13 String password = "123456";14 String name;15 try {16 // 載入驅動程式17 Class.forName(driver);18 // 連續資料庫19 Connection conn = DriverManager.getConnection(url, user, password);20 if (!conn.isClosed())21 System.out.println("Succeeded connecting to the Database!");22 // statement用來執行SQL語句23 Statement statement = conn.createStatement();24 // 要執行的SQL語句25 String sql = "select * from students";26 27 // 結果集28 ResultSet rs = statement.executeQuery(sql);29 System.out.println(rs);30 System.out.println("Succeeded connecting to the Database!");31 while (rs.next()) {32 // 選擇Name這列資料33 name = rs.getString("name");34 // 輸出結果35 System.out.println(name);36 }37 rs.close();//關閉當前的結果集38 statement.close();//關閉statement對象以及所對應的結果集39 conn.close();//關閉當前的串連以及釋放由它所建立的JDBC資源40 } catch (ClassNotFoundException e) {41 System.out.println("Sorry,can`t find the Driver!");42 e.printStackTrace();43 } catch (SQLException e) {44 e.printStackTrace();45 } catch (Exception e) {46 e.printStackTrace();47 }48 }49 }
需要在mysql建立相關資料庫及表。
串連成功,會輸出如下資料。
具體的配置可以參考此連結;http://database.51cto.com/art/201006/204217.htm
下面是擷取表中id欄位:
1 import java.sql.*; 2 3 public class MysqlTest 4 { 5 public static void main(String[] args) 6 { 7 String driver="org.gjt.mm.mysql.Driver"; 8 String url="jdbc:mysql://localhost/xh"; 9 String user="xiaohengdada";10 String password="123456";11 //int id;12 int id1;13 14 15 try16 {17 Class.forName(driver);18 Connection conn=DriverManager.getConnection(url,user,password);19 if (!conn.isClosed())20 System.out.println("Succeeded connecting to be Database!");21 22 Statement statement=conn.createStatement();23 ResultSet rs=statement.executeQuery("select * from students");24 25 System.out.println(rs);26 while(rs.next())27 {28 id1=rs.getInt("id");29 System.out.println(id1);30 }31 rs.close();32 statement.close();33 conn.close(); 34 }35 catch(ClassNotFoundException e)36 {37 System.out.println("Sorry,can‘t find the Driver!");38 e.printStackTrace();39 }40 catch(SQLException e)41 {42 e.printStackTrace();43 }44 catch(Exception e)45 {46 e.printStackTrace();47 }48 }49 }
java串連mysql