JDBC編程六步
第一步:注冊驅動:這里使用第一種寫法用多態(tài)的方式創(chuàng)建驅動對象,后續(xù)有更簡易的方式楷怒,通過反射機制獲取。
第二步:獲取連接:DriverManager.getConnection()方法瓦灶,地址為jdbc:mysql://127.0.0.1:3306/database鸠删,也可以用localhost
第三步:獲取數據庫操作對象:專門執(zhí)行sql語句的對象
第四步:執(zhí)行SQL語句:DQL DML
第五步:處理查詢結果集
第六步:釋放資源:遵循從小到大關閉,分開try...catch
import java.sql.*;
public class Test{
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
//1贼陶、注冊驅動刃泡,左邊為java\sql\下的Driver,右邊為MySQL的Driver.class
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//2碉怔、獲取連接
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/database","root","****");
//3烘贴、獲取數據庫操作對象(Statement專門執(zhí)行sql語句)
statement =connection.createStatement();
//4、執(zhí)行sql
//executeUpdate專門執(zhí)行DML語句(insert delete update)
int count = statement.executeUpdate("insert into dept('字段名') values ('數據')");
System.out.println(count == 1 ? "插入成功" : "插入失敗");
//5撮胧、處理查詢結果集
} catch (SQLException e) {
e.printStackTrace();
}finally {
//6桨踪、釋放資源,從小到大趴樱,分開try
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}