JDBC,即Java Database Connectivity,java數據庫連線。
是一種用於執行SQL語句的Java API,它是 Java中的數據庫連線規範。
JDBC存取數據庫層次結構:
JDBC優勢:
JDBC開發案例:
// 載入JDBC驅動程式:反射,這樣呼叫初始化com.mysql.jdbc.Driver類,
// 即將該類載入到JVM方法 區,並執行該類的靜態方法塊、靜態屬性。
Class.forName("com.mysql.jdbc.Driver");
// 建立數據庫連線
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test? user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
//MySQL數據連線的URL參數格式如下:
jdbc:mysql://伺服器地址:埠/數據庫名?參數名=參數值
Statement statement = connection.createStatement();
ResultSet resultSet= statement.executeQuery(
"select id, sn, name, qq_mail, classes_id from student");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String sn = resultSet.getString("sn");
String name = resultSet.getString("name");
int classesId = resultSet.getInt("classes_id");
System.out.println(String.format("Student: id=%d, sn=%s, name=%s, classesId=%s", id, sn, name, classesId));
}
//關閉結果集
if (resultSet!= null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//關閉命令
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 關閉連線命令
if (connection!= null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JDBC使用步驟總結:
Connection介面實現類由數據庫提供,獲取Connection物件通常有兩種方式:
// 載入JDBC驅動程式
Class.forName("com.mysql.jdbc.Driver");
// 建立數據庫連線
Connection connection = DriverManager.getConnection(url);
DataSource ds = new MysqlDataSource();
((MysqlDataSource) ds).setUrl("jdbc:mysql://localhost:3306/test");
((MysqlDataSource) ds).setUser("root");
((MysqlDataSource) ds).setPassword("root");
Connection connection = ds.getConnection();
以上兩種方式的區別是:
Statement 物件主要是將SQL語句發送到數據庫中。
PreparedStatement物件:
兩種執行SQL的方法:
ResultSet物件它被稱爲結果集,它代表符合SQL語句條件的所有行,並且它通過一套getXXX方法提供 了對這些行中數據的存取。
ResultSet裡的數據一行一行排列,每行有多個欄位,並且有一個記錄指針,指針所指的數據行叫做當前數據行,我們只能來操作當前的數據行。我們如果想要取得某一條記錄,就要使用ResultSet的next() 方法,如果我們想要得到ResultSet裡的所有記錄,就應該使用while回圈。
// 查詢操作
preparedStatement.executeQuery();
// 新增、修改、刪除操作
preparedStatement.executeUpdate();
while (resultSet.next()) {
int xxx = resultSet.getInt("xxx");
String yyy= resultSet.getString("yyy");
...
}
try {
if(resultSet != null){
resultSet.close();
}
if(preparedStatement != null){
preparedStatement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("數據庫錯誤");
}