import java.sql.*;
/**
* 第一個 JDBC 的 HelloWorld 程序, 數據庫訪問MySQL.
*
* @author [email protected]
* @version 0.4 2008-06-17
*/
public class JDBCHelloWorld {
public static void main(String[] args) {
// 1. 註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// Mysql 的驅動
// 先定義變量,後使用和關閉
Connection conn = null;// 數據庫連接
Statement stmt = null;// 數據庫表達式
ResultSet rs = null;// 結果集
try {
// 2. 獲取數據庫的連接
conn = java.sql.DriverManager
.getConnection("jdbc:mysql://localhost:3306/bookdb?useUnicode=true&characterEncoding=GBK","root", "admin");// root是用戶名,密碼爲空
// 3. 獲取表達式
stmt = conn.createStatement();
// 執行插入數據的 SQL
int row = stmt
.executeUpdate("insert into books values('002', 'fanjf1教程1')");
System.out.println("插入了 " + row);
// 4. 執行 SQL
rs = stmt.executeQuery("select * from books");
// 5. 顯示結果集裏面的數據
while (rs.next()) {
System.out.println("編號=" + rs.getString("book_id"));
System.out.println("書名=" + rs.getString("book_name"));
}
// 執行刪除數據的 SQL, 被刪除的記錄的ID爲7
row = stmt.executeUpdate("delete from books where book_id = '001'");
System.out.println("刪除了 " + row);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. 釋放資源,建議放在finally語句中確保都被關閉掉了
try {
rs.close();
} catch (SQLException e) {
}
try {
stmt.close();
} catch (SQLException e) {
}
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
JDBC 的 HelloWorld 程序, 數據庫訪問MySQL
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.