JDBC
什么是JDBC?
jdbc意思就是java连接数据库,Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。”
常用的接口
-
driver接口
//注册JDBC驱动,得到数据库连接 Class.forName("com.mysql.jdbc.Driver");
-
connection接口
//得到一个数据库连接 Connection connection = DriverManager.getConnection(dbPath, userName, pwd); 常用方法: createStatement():创建向数据库发送sql的statement对象。 prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。 prepareCall(sql):创建执行存储过程的callableStatement对象。 setAutoCommit(boolean autoCommit):设置事务是否自动提交。 commit() :在链接上提交事务。 rollback() :在此链接上回滚事务。
-
statement接口
用于执行sql并且得到执行结果
常用Statement方法:
-
- execute(String sql):运行语句,返回是否有结果集
- executeQuery(String sql):运行select语句,返回ResultSet结果集。
- executeUpdate(String sql):运行insert/update/delete操作,返回更新的行数。
- addBatch(String sql) :把多条sql语句放到一个批处理中。
- executeBatch():向数据库发送一批sql语句执行。
String sql = "insert into users values(?,?,?,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 5); preparedStatement.setString(2, "xixi"); preparedStatement.setString(3, "xixi123"); preparedStatement.setString(4, "xixi@qq.com"); preparedStatement.setString(5, "2020-08-07"); // 执行插入 int i = preparedStatement.executeUpdate(); if (i > 0) { System.out.println("success!"); }
4.ResultSet接口
ResultSet提供检索不同类型字段的方法,常用的有:
-
- getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。
- getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。
- getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。
- getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。
- getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。
ResultSet还提供了对结果集进行滚动的方法:
-
- next():移动到下一行
- Previous():移动到前一行
- absolute(int row):移动到指定行
- beforeFirst():移动resultSet的最前面。
- afterLast() :移动到resultSet的最后面。
使用后依次关闭对象及连接:ResultSet → Statement → Connection
-
JDBC的使用方法
下面是一个操作数据库的demo代码
import java.sql.*;
/**
* @author ECHOQIAN
* @version 1.0
* @date 2019/9/16 10:14
*/
public class JdbcTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//设置账户密码
String dbPath = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true";
String userName = "root";
String pwd = "qpy939773";
// 注册JDBC驱动,得到数据库连接
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(dbPath, userName, pwd);
// 编写插入的sql
String sql = "insert into users values(?,?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 5);
preparedStatement.setString(2, "xixi");
preparedStatement.setString(3, "xixi123");
preparedStatement.setString(4, "xixi@qq.com");
preparedStatement.setString(5, "2020-08-07");
// 执行插入
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("success!");
}
// 执行查询的sql
String sql2 = "select * from users";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql2);
ResultSet resultSet = preparedStatement1.executeQuery();
while (resultSet.next()){
String name = resultSet.getString("name");
System.out.println("name: " + name);
}
// 关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();
}
}
JDBC操作数据库事务
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author ECHOQIAN
* @version 1.0
* @date 2019/9/16 15:43
*/
public class JdbcTest2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//设置账户密码
String dbPath = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true";
String userName = "root";
String pwd = "qpy939773";
// 注册JDBC驱动,得到数据库连接
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(dbPath, userName, pwd);
// 设置自动提交为false
connection.setAutoCommit(false);
try {
String sql1 = "update account set money = money+100 where name='A'";
String sql2 = "update account set money = money-100 where name='B'";
int i = connection.prepareStatement(sql1).executeUpdate();
// int error = 1/0;
int j = connection.prepareStatement(sql2).executeUpdate();
// 如果成功的话,就提交事务
if(i>0 && j>0){
connection.commit();
System.out.println(" update success! ");
}
}catch (Exception e){
// 如果事务不成功 那么执行回滚
System.out.println("rollback");
connection.rollback();
}finally {
connection.close();
}
}
}