java jdbc 與mysql串連的基本步驟

來源:互聯網
上載者:User

標籤:設定   keyword   java   cli   mod   comment   屬性   cut   代碼   

 
  1.   

Java與mysql連結的基本步驟:

 

第一步:註冊驅動

方法一:

 

[java] view plain copy 
  1. DriverManager.registerDriver(new com.mysql.jdbc.Driver());  

方法二:設定屬性

 

[java] view plain copy 
  1. System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");  

 

方法三:

 

[java] view plain copy 
  1. Class.forName("com.mysql.jdbc.Driver");  

 

 

第二步:建立串連

 

[java] view plain copy 
  1. Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");  

第三步:建立語句

 

 

[java] view plain copy 
  1. Statement st = (Statement) conn.createStatement();  

第四步:執行語句

 

第五步:處理結果

第六步:釋放資源

測試代碼:

 

[java] view plain copy 
    1. import java.sql.DriverManager;  
    2. import java.sql.ResultSet;  
    3. import java.sql.SQLException;  
    4.   
    5. import com.mysql.jdbc.Connection;  
    6. import com.mysql.jdbc.Statement;  
    7.   
    8. public class Demo {  
    9.     public static void main(String[] args) {  
    10.         Demo d = new Demo();  
    11.         try {  
    12.             d.test();  
    13.         } catch (SQLException e) {  
    14.             // TODO Auto-generated catch block  
    15.             e.printStackTrace();  
    16.         }  
    17.     }  
    18.   
    19.     static void test() throws SQLException {  
    20.         // 第一步:註冊驅動  
    21.         DriverManager.registerDriver(new com.mysql.jdbc.Driver());  
    22.         // 第二步:建立串連  
    23.         Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");  
    24.         // 第三步:建立語句  
    25.         Statement st = (Statement) conn.createStatement();  
    26.         // 第四步:執行語句,並將結果取出  
    27.         ResultSet rs = st.executeQuery("select * from mytable");  
    28.   
    29.         // 第五步:處理結果  
    30.         while (rs.next()) {  
    31.             System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t"  
    32.                     + rs.getObject(3));  
    33.         }  
    34.           
    35.         //第六步:釋放資源  
    36.         rs.close();  
    37.         st.close();  
    38.         conn.close();  
    39.     }  
    40. }  

java 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.