import java.sql.*;
public class JDBCHelloWorld
{
public static void main(String[] args)
{ // 1. 註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}// Mysql 的驅動
// 先定義變數,後使用和關閉
Connection conn = null;// 資料庫連接
Statement stmt = null;// 資料庫運算式 ResultSet rs = null;// 結果集
ResultSet rs = null;
try {
// 2. 擷取資料庫的串連
conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK","root", null);// root是使用者名稱,密碼為空白
// 3. 擷取運算式
stmt = conn.createStatement();
// 執行插入資料的 SQL
int row = stmt.executeUpdate("insert into Student(username, password, age) values('張三', '1234', 20)");
System.out.println("插入了 " + row);
// 4. 執行 SQL
rs = stmt.executeQuery("select * from Student");
// 5. 顯示結果集裡面的資料
while (rs.next())
{
System.out.println("編號=" + rs.getInt(1));
System.out.println("學生姓名=" + rs.getString("username"));
System.out.println("密碼=" + rs.getString("password"));
System.out.println("年齡=" + rs.getString("age"));
}
// 執行刪除資料的 SQL, 被刪除的記錄的ID為7
row = stmt.executeUpdate("delete from student where id = 7");
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)
{
}
}
}
}