JDBC原始版本,未封裝

JDBC原始版本,未封裝

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/mybatis?characterEncoding=utf-8", "root", "root");
// 定義sql語句 ?表示佔位符
String sql = "select * from user where username = ?";
// 獲取預處理statement
preparedStatement = connection.prepareStatement(sql);
// 設置參數,第一個參數爲sql語句中參數的序號(從1開始),第二個參數爲設置的參數值
preparedStatement.setString(1, "王五");
// 向數據庫發出sql執行查詢,查詢出結果集
resultSet = preparedStatement.executeQuery();
// 遍歷查詢結果集
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + "  " + resultSet.getString("username"));
}
} 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();
}
}
}
}
 
上邊使用jdbc的原始方法(未經封裝)實現了查詢數據庫表記錄的操作。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章