public class JDBCTest {
/**
* 使用JDBC連接并操作mysql數(shù)據(jù)庫
*/
public static void main(String[] args) {
// 數(shù)據(jù)庫驅動類名的字符串
String driver = "com.mysql.jdbc.Driver";
// 數(shù)據(jù)庫連接串
String url = "jdbc:mysql://127.0.0.1:3306/test";
// 用戶名
String username = "root";
// 密碼
String password = "1234";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1巧娱、加載數(shù)據(jù)庫驅動( 成功加載后,會將Driver類的實例注冊到DriverManager類中)
Class.forName(driver );
// 2语盈、獲取數(shù)據(jù)庫連接
conn = DriverManager.getConnection(url, username, password);
// 3漆羔、獲取數(shù)據(jù)庫操作對象
stmt = conn.createStatement();
// 4蜒程、定義操作的SQL語句
String sql = "select * from user where id = 100";
// 5降盹、執(zhí)行數(shù)據(jù)庫操作
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、關閉對象蔬捷,回收數(shù)據(jù)庫資源
if (rs != null) { //關閉結果集對象
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) { // 關閉數(shù)據(jù)庫操作對象
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) { // 關閉數(shù)據(jù)庫連接對象
try {
if (!conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
這是一個jdbc的簡單代碼垄提。