原始jdbc連線資料庫的程式碼
阿新 • • 發佈:2019-01-10
//此連線是針對於mysql的連線
public class MybatisJdbcConnection {
public static void main(String[] args){Connection conn = null;
ResultSet res = null;
PreparedStatement prepareStatement=null;
try {
//載入資料庫驅動
Class.forName("com.mysql.jdbc.Driver");
//獲得資料庫連線池
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
//定義sql語句
String sql = "select * from user where username = ?";
//得到預處理statement
prepareStatement = conn.prepareStatement(sql);
//設定引數,?代表的是需要查詢的條件也就是引數從1開始,有幾個就設定幾個
prepareStatement.setString(1, "王五");
//向資料庫發出sql執行查詢 ,查詢出結果集
res = prepareStatement.executeQuery();
//遍歷結果集
while(res.next()){
String userid = res.getString("id");
String username = res.getString("username");
System.out.println("..."+userid+"...."+username+"....");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//釋放資源
if(res!=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(prepareStatement!=null){
try {
prepareStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}