JDBC编程六步
第一步:注册驱动:这里使用第一种写法用多态的方式创建驱动对象,后续有更简易的方式,通过反射机制获取。
第二步:获取连接:DriverManager.getConnection()方法,地址为jdbc:mysql://127.0.0.1:3306/database,也可以用localhost
第三步:获取数据库操作对象:专门执行sql语句的对象
第四步:执行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专门执行sql语句)
statement =connection.createStatement();
//4、执行sql
//executeUpdate专门执行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();
}
}
}
}
}