DriverManager(驱动管理类)作用:1.注册驱动 2.获取数据库连接
注册驱动使用的是DriverManager:Class.forName("com.mysql.jdbc.Driver")中Driver的源码包含:
static {
System.err.println("Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.");
}
它随着DriverManager加载自动执行
获取连接的url(连接路径):语法:jdbc:mysql://ip地址或域名:端口号:/数据库名称?参数键值对&参数键值对1
例:jdbc:mysql:///db1?useSSl=false
(连接本机MySQL,且MySQL服务器默认端口是3306,则地址或域名:端口号可省略)
(配置useSSL=false参数,禁用安全连接方式,解决警告提示)
Connection(数据库连接对象)作用:1.获取执行SQL的对象 2.管理事务
获取执行SQL的对象:
普通执行SQL对象:Statement createStatement()
预编译SQL的执行SQL对象,防止SQL注入:PreparedStatement prepareStatement
执行存储过程对象:CallableStatement prepareCall(sql)
事务管理:
MySQL事务管理:
开启事务:BEGIN;/START TRANSACTION;
设置手动提交:set @@autocommit;
提交事务:COMMIT;
回滚事务:ROLLBACK;
默认自动提交
JDBC事务管理(Connection接口定义了3个对应的方法):
开启事务:setAutoComment(boolean autoCommit):true为自动提交,false为手动提交(开启事务)
提交事务:commit()
回滚事务:rollback()
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo1 {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql:///db1?useSSl=false";
String name = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, name, password);
String sql = "update account set money = 12000 where id = 1";
String sql1 = "update account set money = 12000 where id = 2";
Statement stmt = conn.createStatement();
Statement stmt1 = conn.createStatement();
try { //快速使用try catch,ctrl+alt+T
//开启事务
conn.setAutoCommit(false);
int i = stmt.executeUpdate(sql);
System.out.println(i);
int i1 = stmt1.executeUpdate(sql1);
System.out.println(i1);
} catch (Exception e) {
//回滚事务
conn.rollback();
e.printStackTrace();
}
conn.close();
stmt.close();
}
}
网友评论