JDBC中的核心類有:DriverManager、Connection、Statement,和ResultSet!mysql
DriverManger(驅動管理器)的做用有兩個:sql
l 註冊驅動:這可讓JDBC知道要使用的是哪一個驅動;Class.forName(「com.mysql.jdbc.Driver」)數據庫
l 獲取Connection:若是能夠獲取到Connection,那麼說明已經與數據庫鏈接上了。mybatis
Connection con = DriverManager.getConnection(「jdbc:mysql://localhost:3306/mydb1」,」root」,」123」);學習
Connection對象表示鏈接,與數據庫的通信都是經過這個對象展開的:spa
l Connection最爲重要的一個方法就是用來獲取Statement對象;對象
Statement是用來向數據庫發送SQL語句的,這樣數據庫就會執行發送過來的SQL語句:utf-8
l void executeUpdate(String sql):執行更新操做(insert、update、delete等);資源
l ResultSet executeQuery(String sql):執行查詢操做,數據庫在執行查詢後會把查詢結果,查詢結果就是ResultSet;get
(後面咱們使用的都是PrepareStatement:預編譯的語句,它的好處有三點,防止sql的攻擊,提升代碼可讀性,提升效率)
PreparedStatement最大的好處就是在於重複使用同一模板,給予其不一樣的參數來重複的使用它。這纔是真正提升效率的緣由。
ResultSet對象表示查詢結果集,只有在執行查詢操做後纔會有結果集的產生。結果集是一個二維的表格,有行有列。操做結果集要學習移動ResultSet內部的「行光標」,以及獲取當前行上的每一列上的數據:
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", "password");
//三、定義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();
}
}
}
}