mysql 數據庫驅動包 mysql-connector-java-x.x.x-bin.jar
pom文件
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
//數據庫連接
Connection connection = null;
//預編譯的Statement,使用預編譯的Statement提高數據庫性能
PreparedStatement preparedStatement = null;
//結果 集
ResultSet resultSet = null;
try {
//加載數據庫驅動
Class.forName("com.mysql.jdbc.Driver");
//通過驅動管理類獲取數據庫鏈接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xiatest?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();
}
}
}