JDBC入門之一--串連Mysql實驗

來源:互聯網
上載者:User

標籤:next   建立   eclips   imp   rom   success   erro   虛擬機器   pass   

工具:mysql-connector-java-5.1.40、eclipse

1)首先要將mysql-connector-java包整合到eclipse中,右擊項目,然後選擇build path,出現如此,然後OK就可以了!

 

2)建立一個測試類別,測試連接,代碼如下 1 import java.sql. 2 //Connection這個類在Mysql-connector-java中也有,但是我們是在java虛擬機器中跑的,所以用的是java.sql包中的內容。

 
 1 import java.sql.*; 2  3 public class MysqlConnection { 4     public static void main(String args[]){ 5                 //1)載入mysql磁碟機 6         try { 7             Class.forName("com.mysql.jdbc.Driver"); 8             System.out.println("Success loading driver!"); 9         } catch (Exception e) {10             // TODO: handle exception11             System.out.print("Error loading driver!");12             e.printStackTrace();13         }14         //2)建立與mysql串連15                 //getConnection的三個參數,url:只能連線協定,串連主機,和連接埠號碼,以及要串連的資料庫;user:串連到資料庫中的使用者名稱;password:串連密碼16         try {17             Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/world","root","538769");18             System.out.println("connect to world!");19                         //3)通過connection,建立statement20             Statement stm = connection.createStatement();21             //4)resultset中存放查詢之後的結果22             ResultSet rSet = stm.executeQuery("select * from city");23             //ResultSet中的next方法是判斷下一個是否為空白24             while(rSet.next()){25                 System.out.println("the City " + rSet.getString("ID")+" is " + rSet.getString("Name"));26                 //System.out.println(rSet.getString("ID","Name"));27             28             }29             30         } catch (Exception e) {31             // TODO: handle exception32             System.out.println("error get data!");33             e.printStackTrace();34         }35         36     }37 }                 

3)將源碼 運行起來,可以看到查詢到了結果.

 

JDBC入門之一--串連Mysql實驗

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.