1.載入驅動(mysql的驅動是com.mysql.jdbc.Driver,SqlServer的驅動是 com.microsoft.sqlserver.jdbc.SQLServerDriver) 2.載入資料庫的連接(url, username,password) 3.編寫sql語句(String ...
1.載入驅動(mysql的驅動是com.mysql.jdbc.Driver,SqlServer的驅動是 com.microsoft.sqlserver.jdbc.SQLServerDriver)
2.載入資料庫的連接(url, username,password)
3.編寫sql語句(String sql="select * from grade where gradeName = ?";)
4.遍歷查詢結果 【while (resultSet.next()) {
System.out.println(resultSet.getInt("gradeId") + " " + resultSet.getString("gradeName"));
}】
5.關閉資源(從後向前關閉資源 )
public class Test {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 載入資料庫驅動
Class.forName("com.mysql.jdbc.Driver");
// 通過驅動管理類獲取資料庫鏈接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool?characterEncoding=utf-8", "root", "root");
// 定義sql語句 ?表示占位符
String sql = "select * from grade where gradeName = ?";
// 獲取預處理statement
preparedStatement = connection.prepareStatement(sql);
// 設置參數,第一個參數為sql語句中參數的序號(從1開始),第二個參數為設置的參數值
preparedStatement.setString(1, "二年級");
// 向資料庫發出sql執行查詢,查詢出結果集
resultSet = preparedStatement.executeQuery();
// 遍歷查詢結果集
while (resultSet.next()) {
System.out.println(resultSet.getInt("gradeId") + " " + resultSet.getString("gradeName"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 釋放資源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}