JDBC操作資料庫的基本步驟__資料庫

來源:互聯網
上載者:User

JDBC操作資料庫的基本步驟:

    1)載入(註冊)資料庫驅動(到JVM)。

    2)建立(擷取)資料庫連接。

    3)建立(擷取)資料庫操作對象。

    4)定義操作的SQL語句。

    5)執行資料庫操作。

    6)擷取並操作結果集。

   7)關閉對象,回收資料庫資源(關閉結果集-->關閉資料庫操作對象-->關閉串連)。

package com.yangshengjie.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCTest {/** * 使用JDBC串連並操作mysql資料庫 */public static void main(String[] args) {// 資料庫驅動類名的字串String driver = "com.mysql.jdbc.Driver";// 資料庫連接串String url = "jdbc:mysql://127.0.0.1:3306/jdbctest";// 使用者名稱String username = "root";// 密碼String password = "mysqladmin";Connection conn = null;Statement stmt = null;ResultSet rs = null;try {// 1、載入資料庫驅動( 成功載入後,會將Driver類的執行個體註冊到DriverManager類中)Class.forName(driver );// 2、擷取資料庫連接conn = DriverManager.getConnection(url, username, password);// 3、擷取資料庫操作對象stmt = conn.createStatement();// 4、定義操作的SQL語句String sql = "select * from user where id = 100";// 5、執行資料庫操作rs = stmt.executeQuery(sql);// 6、擷取並操作結果集while (rs.next()) {System.out.println(rs.getInt("id"));System.out.println(rs.getString("name"));}} catch (Exception e) {e.printStackTrace();} finally {// 7、關閉對象,回收資料庫資源if (rs != null) { //關閉結果集對象try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) { // 關閉資料庫操作對象try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) { // 關閉資料庫連接對象try {if (!conn.isClosed()) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}}}} 


聯繫我們

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