JAVA_JDBC

JDBC概念: 使用JAVA代碼操作數(shù)據(jù)庫


-----------------------------

DEMO:

package com.company.jdbc;

import java.sql.*;

public class Main {

// 數(shù)據(jù)庫地址

? ? static Stringurl ="jdbc:mysql://localhost:3306/mysql";

? ? static Stringusername ="root";

? ? static Stringpassword ="12345678";

? ? public static void main(String[] args)? {

// 1.加載驅(qū)動(開發(fā)推薦的方式)

? ? ? ? System.out.println("Hello,Java~~~");

? ? ? ? Connection connection =null;

? ? ? ? ResultSet resultSet =null;

? ? ? ? PreparedStatement preparedStatement =null;

? ? ? ? try {

// 2.獲取Connection對象 Collection是數(shù)據(jù)庫編程中最重要的一個對象,客戶端與數(shù)據(jù)庫所有交互都是通過connection對象完成的

? ? ? ? ? ? connection = DriverManager.getConnection(url,username,password);

? ? ? ? ? ? // SQL語句

? ? ? ? ? ? String sql ="select * from student where name = '張三'";

? ? ? ? ? ? // 數(shù)據(jù)庫查詢方法,執(zhí)行SQL語句

? ? ? ? ? ? preparedStatement = connection.prepareStatement(sql);

? ? ? ? ? ? // 將查詢到的結(jié)果賦值到ResultSet對象

? ? ? ? ? ? resultSet = preparedStatement.executeQuery(sql);

? ? ? ? ? ? // 遍歷結(jié)果

? ? ? ? ? ? while (resultSet.next()) {

String name = resultSet.getString("name");

? ? ? ? ? ? ? ? System.out.println("name:" + name);

? ? ? ? ? ? }

}catch (SQLException throwables) {

throwables.printStackTrace();

? ? ? ? }finally {

// 釋放資源

? ? ? ? ? ? if (resultSet !=null) {

try {

resultSet.close();

? ? ? ? ? ? ? ? }catch (SQLException throwables) {

throwables.printStackTrace();

? ? ? ? ? ? ? ? }

}

if (preparedStatement !=null) {

try {

preparedStatement.close();

? ? ? ? ? ? ? ? }catch (SQLException throwables) {

throwables.printStackTrace();

? ? ? ? ? ? ? ? }

}

}

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容