JDBC
JDBC(Java Database Connectivity)
数据库连接规范一套接口由-sun-公司提供的">Java 数据库连接规范(一套接口)由 Sun 公司提供的
JDBC 核心类
DriverManager 创建连接
Connection 连接类
Statement 执行 sql 语句
ResultSet 结果集
JDBC连接步骤
1.注册驱动
2.获取链接 connection
3.获取 sql 语句的执行对象 Statement
4.执行 sql 语句 返回结果集 ResultSet
5.处理结果集
6.关闭资源
注册驱动
// 需要注意的是,这种注册方式,相当于注册了两遍
// 因为 Driver 类的内部的静态代码块已经注册了一遍
DriverManager.registerDriver(new Driver));
// 直接把该类加载到内存当中,参数是全限定类名(包名 + 类名)
Class.forName("com.mysql.jdbc.Driver");
获取连接对象
// url 是访问数据库连接地址
// myjdbc 为数据库名
String url = "jdbc:mysql://localhost:3306/myjdbc";
连接方式一:
// root 数据库用户名
// 123456 数据库密码
Connection connection = DriverManager.getConnection(url, "root", "123456");
连接方式二:
Properties info = new Properties();
// 添加用户名和密码
// 注意:键值别拼错了
info.setProperty("user", "root");
info.setProperty("password", "123456);
Connection connection = DriverManage.getConnection(url, info);
连接方式三:相当于使用了一个 get 请求,携带参数访问链接
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url);
// 获取执行 sql 语句的对象 Statement
Statement statement = connection.createStatement();
// 执行 sql 语句, 返回结果集
// 结果集中添加的索引要和查询语句中的字段对应
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
// 处理结果集
// 循环遍历结果集,输出结果
// 有记录 next() 方法返回 true, 没有返回 false
while(resultSet.next()) {
// 打印数据
// 注意:查询数据库时,索引从1开始
System.out.print(resultSet.getObject(1));
System.out.print(resultSet.getObject(2));
System.out.print(resultSet.getObject(3));
System.out.print(resultSet.getObject(4));
System.out.println(resultSet.getObject(5));
}
// 关闭资源
resultSet.close();
statement.close();
connection.close();
测试增删改查
@Test
public void testInsert() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql = "insert into users values(4, 'zs', '123', '123@163.com', '2018-01-01
int row = statement.executeUpdate(sql);
System.out.println(row);
if (row > 0) {
System.out.println("插入成功");
}
statement.close();
connection.close();
}
@Test
public void testUpdate() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql = "update users set name='zs";
int row = statement.executeUpdate(sql);
System.out.println(row);
if (row > 0) {
System.out.println("更新成功");
}
statement.close();
connection.close();
}
@Test
public void testDelete() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url)