JDBC
JDBC: Java Database Connectivity SUN 公司提供的一套操作数据库的标准规范。
一、 JDBC与数据库驱动
接口与实现的关系
二、JDBC规范(掌握四个核心对象)
- DriverManager : 注册驱动
- Connection:与数据库进行连接
- Statement: 操作数据库SQL语句的对象
- ResultSet: 结果集或者一张虚拟表
public static void main(String[] args) throws SQLException {
System.out.println("test jjjjDemo");
Connection con = null;
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2", "root", "password");
Statement stmt = conn.createStatement(); // 得到执行SQL的对象
ResultSet rs = stmt.executeQuery("select * from employee");
while (rs.next()) {
System.out.println(rs.getObject(1)); // 访问数据库的第一列
System.out.println(rs.getObject(2)); // // 访问数据库的第二列
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
System.out.println(rs.getObject(6));
System.out.println(rs.getObject(7));
System.out.println(rs.getObject(8));
System.out.println("================================");
}
// 结果集关闭 释放支援
rs.close();
stmt.close();
conn.close();
}
DriverManager 优缺点
导致注册两次
强烈依赖数据库的驱动 jar
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
public Driver() throws SQLException {
}
// 静态代码块随着类的加载而加载,导致注册两侧
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
改为直接加载驱动
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("test jjjjDemo");
Connection con = null;
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver"); // 加载驱动(反射)
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2", "root", "password");
Statement stmt = conn.createStatement(); // 得到执行SQL的对象
ResultSet rs = stmt.executeQuery("select * from employee");
while (rs.next()) {
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
System.out.println(rs.getObject(6));
System.out.println(rs.getObject(7));
System.out.println(rs.getObject(8));
System.out.println("================================");
}
// 结果集关闭 释放支援
rs.close();
stmt.close();
conn.close();
}
URL:SUN 公司与数据库厂商之间的协议
协议 子协议 IP 端口号 数据库
jdbc: mysql: // localhost: 3306 /mydb2
网友评论