Java使用JDBC串連資料庫的實現方法_java

來源:互聯網
上載者:User

本文執行個體講述了Java使用JDBC串連資料庫的實現方法,是Java資料庫程式設計裡非常實用的重要技巧。分享給大家供大家參考。具體如下:

JDBC(Java Data Base Connectivity)資料庫連接,通常我們在編寫web應用或java應用程式要串連資料庫時就要使用JDBC。使用JDBC串連資料庫一般步驟有:

1、載入驅動程式

Class.forName(driver);

2、建立連線物件

Connection con = DriverManager.getConnection(url,username,password);

3、建立sql語句執行對象
4、執行sql語句
5、對執行結果進行處理
6、關閉相關的連線物件(順序跟聲明的順序相反)

下面是以建立與MySQL資料庫連接的例子,其他資料庫的過程類似:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DBConnection{public static void main(String[] args){String driver = "com.mysql.jdbc.Driver";//localhost指本機,也可以用本地ip地址代替,3306為MySQL資料庫的預設連接埠號碼,“user”為要串連的資料庫名String url = "jdbc:mysql://localhost:3306/user";//填入資料庫的使用者名稱跟密碼String username = "test";String password = "test";String sql = "select * from user";//編寫要執行的sql語句,此處為從user表中查詢所有使用者的資訊try{Class.forName(driver);//載入驅動程式,此處運用隱式註冊驅動程式的方法}catch(ClassNotFoundException e){e.printStackTrace();}try{Connection con = DriverManager.getConnection(url,username,password);//建立連線物件Statement st = con.createStatement();//建立sql執行對象ResultSet rs = st.executeQuery(sql);//執行sql語句並返回結果集while(rs.next())//對結果集進行遍曆輸出{System.out.println("username: "+rs.getString(1));//通過列的標號來獲得資料System.out.println("useradd: "+rs.getString("useradd"));//通過列名來獲得資料System.out.println("userage: "+rs.getInt("userage"));}//關閉相關的對象if(rs != null){try{rs.close();}catch(SQLException e){e.printStackTrace();}}if(st != null){try{st.close();}catch(SQLException e){e.printStackTrace();}}if(con !=null){try{con.close();}catch(SQLException e){e.printStackTrace();}}}catch(SQLException e){e.printStackTrace();}}}

相信本文所述對大家的Java資料庫程式設計有一定的借鑒價值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.