標籤:mysq out 動態sql 一點 .com 回收 mysql 註冊 ima
1、下載驅動程式並部署
我們在對資料庫進行操作之前要先串連到資料庫(這裡以Intellij Idea串連MySQL為例)。
(1)、建立一個Idea工程,下載資料庫連接驅動程式,並放到Idea的工程檔案夾下。
(2)、載入JDBC驅動程式
在串連資料庫之前,首先要載入想要串連的資料庫的驅動到JVM(Java虛擬機器),可以用forName(String className)方法實現。
2、串連到資料庫並擷取資料庫連接對象
(1)JDBC串連所需的參數(user,password,url)
a、user 使用者名稱
b、password 密碼
c、url 定義了串連資料庫時的協議、子協議、資料來源標識。
(2)建立資料庫的串連
a、要串連資料庫,需要向java.sql.DriverManager請求並獲得Connection對象,該對象就代表一個資料庫的串連。
b、使用DriverManager的getConnectin(String url , String username , String password )方法傳入指定的欲串連的資料庫的路徑、資料庫的使用者名稱和
密碼來獲得。
(3)建立一個preparedStatement
要執行SQL語句,必須獲得java.sql.Statement執行個體,Statement執行個體分為以下3種類型:
a、執行靜態SQL語句。通常通過Statement執行個體實現。
b、執行動態SQL語句。通常通過PreparedStatement執行個體實現。
c、執行資料庫預存程序。通常通過CallableStatement執行個體實現
3、執行SQL語句
Statement介面提供了三種執行SQL語句的方法:executeQuery 、executeUpdate和execute
資料庫連接對象conn調用上面的statement方法(靜態sql語句),將SQL語句以字串的形式賦給stu_Mgr_select_select_all
操作結果集的兩種情況:
1、執行更新返回的是本次操作影響到的記錄。
2、執行查詢返回的結果是一個ResultSet對象(以下是查詢)
4、關閉JDBC對象資源
操作完成以後要把所有使用的JDBC對象全都關閉,以釋放JDBC資源.
======================================================================================分割線
第一次發部落格,如有不正確的地方,歡迎大家指正。
原始碼放下面,驅動程式可以到sun公司下載最新版
package studentScoreMgrSystem;
//引入介面,串連資料庫,執行資料庫操作,使用jdbc
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class selectStudentMssg_handler implements studentMssg_interface {
public void selectStu() {
System.out.println("尋找學生資訊");
//載入jdbc驅動程式套件
String driver = "com.mysql.jdbc.Driver";
// 資料庫連接串
String url = "jdbc:mysql://127.0.0.1:3306/curd";
// 使用者名稱
String username = "root";
// 密碼
String password = "4950";
Connection conn = null;
Statement stu_Mgr_select_stmt = null;
ResultSet stu_Mgr_select_rs = null;
try {
// 1、載入資料庫驅動( 成功載入後,會將Driver類的執行個體註冊到DriverManager類中)
Class.forName(driver);
// 2、擷取資料庫連接
conn = DriverManager.getConnection(url, username, password);
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// 3、擷取資料庫操作對象
stu_Mgr_select_stmt = conn.createStatement();
// 4、定義操作的SQL語句
String stu_Mgr_select_select_all = "select * from stu_score";
// 5、執行資料庫操作,結果存到stu_Mgr_select_中
stu_Mgr_select_rs = stu_Mgr_select_stmt.executeQuery(stu_Mgr_select_select_all);
// 6、擷取並操作結果集
} catch (Exception e) {
e.printStackTrace();
}finally {
// 7、關閉對象,回收資料庫資源
if (stu_Mgr_select_rs != null) { //關閉結果集對象
try {
stu_Mgr_select_rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stu_Mgr_select_stmt != null) { // 關閉資料庫操作對象
try {
stu_Mgr_select_stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) { // 關閉資料庫連接對象
try {
if (!conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Java學習——關於JDBC的一點分享