public class ConnectionTest {
/**
* 方式一
* @throws SQLException
*/
@Test
public void testConnection1() throws SQLException {
//1、获取Driver的实现类对象
Driver driver=new com.mysql.jdbc.Driver();
//2、提供要连接的数据库:stu为其中的一个数据库名
String url="jdbc:mysql://localhost:3306/stu";
//3、封装用户名和密码
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
/**
* 方式二:对方式一的迭代:在如下的程序中不出现第三方的API,使程序具有更好的可移植性
*/
@Test
public void testConnection2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//1、获取Driver实现类对象
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver= (Driver) aClass.newInstance();
//2、提供需要连接的数据库
String url="jdbc:mysql://localhost:3306/stu";
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
//4、获取连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
/**
* 方式三:迭代方式二:使用DriverManger替换Driver
* @throws Exception
*/
@Test
public void testConnection3() throws Exception {
//1、获取Driver实现类对象
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver= (Driver) aClass.newInstance();
//2、获取基本信息
String url="jdbc:mysql://localhost:3306/stu";
String user="root";
String password="123456";
//3、注册驱动
DriverManager.registerDriver(driver);
//4、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
/**
* 方式四:只加载驱动,不用显式注册驱动
* @throws Exception
*/
@Test
public void testConnection4() throws Exception {
//1、获取基本信息
String url="jdbc:mysql://localhost:3306/stu";
String user="root";
String password="123456";
//2、加载Driver
Class.forName("com.mysql.jdbc.Driver");
//3、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
/**
* 最终版
*/
@Test
public void testConnection5() throws ClassNotFoundException, SQLException, IOException {
//1、读取配置文件中的基本信息
FileInputStream fs = new FileInputStream("jdbc.properties");
Properties ps = new Properties();
ps.load(fs);
String user = ps.getProperty("user");
String password = ps.getProperty("password");
String url = ps.getProperty("url");
String driver = ps.getProperty("driver");
//2、加载驱动
Class.forName(driver);
//3、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
通过调用Connection对象的createStatement()方法创建对象。该对象执行静态的SQL语句,并且返回执行结果
Statement接口中定义了下列方法用于执行SQL语句
int excuteUpdate(String sql);//执行更新操作INSERT、UPDATE、DELETE
ResultSet executeQuery(String sql);//执行查询操作SELECT
使用Statement操作数据表存在弊端:
SQL注入是利用某些系统没有对用户输入的数据进行充分的检验,而在用户输入数据中注入非法的SQL语句段或命令(如:SELECT user, password FROM user_table WHERE user='a’OR1='ADN password=‘OR’1’=‘1’),从而利用系统对SQL引擎完成恶意行为的做法
对于Java而言,要防范SQL注入,则使用PreparedStatement取代Statement
public class PreparedStatementUpdateTest {
@Test
public void test() {
Connection conn = null;
PreparedStatement pps = null;
try {
FileInputStream fs = new FileInputStream("jdbc.properties");
Properties ps = new Properties();
ps.load(fs);
String user=ps.getProperty("user");
String password=ps.getProperty("password");
String url=ps.getProperty("url");
String driver=ps.getProperty("driver");
//2、加载驱动
Class.forName(driver);
//3、获取连接
conn = DriverManager.getConnection(url, user, password);
//4、预编译SQL语句,返回PreparedStatement实例
String sql="insert into book(name,author,price,type)values(?,?,?,?)";
pps = conn.prepareStatement(sql);
//5、填充占位
pps.setString(1,"三国演义");
pps.setString(2,"罗贯中");
pps.setString(3,"30");
pps.setString(4,"小说");
//6、执行操作
pps.execute();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7、关闭资源
try {
if(pps!=null){
pps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class InsertTest {
@Test
public void test(){
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
//方式三:设置不允许自动提交数据
conn.setAutoCommit(false);
String sql="insert into goods(name)values(?)";
ps = conn.prepareStatement(sql);
final int value=1000000;
long start = System.currentTimeMillis();
for (int i = 0; i <value ; i++) {
ps.setObject(1,"name_"+i);
//方式一
// ps.execute();
//方式二
//1、“攒”SQL
ps.addBatch();
if(i%500==0){
//2、执行batch
ps.executeBatch();
//3、清空batch
ps.clearBatch();
}
}
//统一提交数据
conn.commit();
long end = System.currentTimeMillis();
System.out.println("执行时间为:"+(end-start));
//方式一执行时间为:29135
//方式二执行时间为:279 1000000--->执行时间为:9568
//方式三:1000000--->执行时间为:5000
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps);
}
}
}
类型 | 大小(单位:字节) |
---|---|
TinyBlob | 最大 255 |
Blob | 最大 65K |
MediumBlob | 最大 16M |
LongBlob | 最大4 G |
public class BlobTest {
/**
* 向数据表customer中插入Blob类型的字段
* @throws Exception
*/
@Test
public void testInsert() throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql="insert into customers(name,image)values(?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,"房东的猫");
FileInputStream fs = new FileInputStream(new File("房东的猫1.jpg"));
ps.setObject(2,fs);
ps.execute();
JDBCUtils.closeResource(conn,ps);
}
}
public class BlobTest {
@Test
public void testQuery() {
Connection conn = null;
PreparedStatement ps = null;
FileOutputStream fos =null;
InputStream bs =null;
ResultSet rs =null;
try {
conn = JDBCUtils.getConnection();
String sql="select id,name,image from customers where id=?";
ps = conn.prepareStatement(sql);
ps.setInt(1,2);
rs = ps.executeQuery();
if(rs.next()){
//1、方式一
/*int id=rs.getInt(1);
String name = rs.getString(2);*/
//2、方式二
int id = rs.getInt("id");
String name = rs.getString("name");
Customer cust = new Customer(id, name);
System.out.println(cust.toString());
//将Blob类型字段下载下来,以文件形式保存在本地
Blob image = rs.getBlob("image");
bs = image.getBinaryStream();
fos = new FileOutputStream(new File("zjl2.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len=bs.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bs!=null){
bs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,ps);
}
}
}
/**
* @Description TODO
* @Author YunShuaiWei
* @Date 2020/6/22 11:44
* @Version
**/
public class TransactionUpdate {
@Test
public void testUpdate() {
Connection conn = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
try {
conn = JDBCUtils.getConnection();
//关闭自动提交
conn.setAutoCommit(false);
String sql1 = "update account set money=money-100 where id=?";
String sql2 = "update account set money=money+100 where id=?";
ps1 = conn.prepareStatement(sql1);
ps1.setInt(1, 2);
ps1.execute();
//模拟异常
int i = 1 / 0;
ps2 = conn.prepareStatement(sql2);
ps2.setInt(1, 3);
ps2.execute();
//数据的提交
conn.commit();
} catch (Exception e) {
e.printStackTrace();
try {
if (conn != null) {
//事务回滚
conn.rollback();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} finally {
try {
if (ps1 != null) {
ps1.close();
}
if (ps2 != null) {
ps2.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
隔离级别 | 描述 |
---|---|
READ UNCOMMITED(读未提交数据) | 允许事务读取未被其他事务提交的变更,脏读、不可重复读和幻读的问题都会出现 |
READ COMMITED (读已提交数据) | 只允许事务读取已经被其他事务提交的变更,可以避免脏读,但不可重复读和幻读问题仍然可能出现 |
REPEABLE READ (不可重复读) | 确保事务可以多次从一个字段中读取相同的值,在这个事务持续期间,禁止其他事务对这个字段进行更新,可以避免脏读和不可重复读,但幻读的问题仍然存在 |
(SERIALIZABLE (串行化)) | 确保事务可以从一个表中读取相同的行,在这个事务持续期间,禁止其他事务对该表执行插入,更新和删除操作,所有并发问题都可以避免,但性能十分低 |
/**
* @Description TODO
* @Author YunShuaiWei
* @Date 2020/6/22 21:21
* @Version
**/
public class DataSourceTest {
@Test
public void testGetConnection() throws Exception {
//获取c3p0数据库连接池
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/ysw");
cpds.setUser("root");
cpds.setPassword("****");
//初始数据库连接数
cpds.setInitialPoolSize(10);
//获取连接
Connection conn = cpds.getConnection();
System.out.println(conn);
}
//使用配置文件
@Test
public void testGetConnection1() throws Exception {
ComboPooledDataSource cpds = new ComboPooledDataSource("hello");
Connection conn = cpds.getConnection();
System.out.println(conn);
}
}
<c3p0-config>
<named-config name="hello">
<property name="user">rootproperty>
<property name="password">****property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/yswproperty>
<property name="driverClass">com.mysql.jdbc.Driverproperty>
<property name="acquireIncrement">5property>
<property name="initialPoolSize">10property>
<property name="minPoolSize">50property>
<property name="maxPoolSize">1000property>
<property name="maxStatements">50property>
<property name="maxStatementsPerConnection">5property>
named-config>
c3p0-config>
@Test
public void druidTest() throws Exception {
Properties p = new Properties();
FileInputStream fs = new FileInputStream(new File("druid.properties"));
p.load(fs);
DataSource ds = DruidDataSourceFactory.createDataSource(p);
Connection conn = ds.getConnection();
System.out.println(conn);
}
url=jdbc:mysql://localhost:3306/ysw
username=root
password=****
driverClassName=com.mysql.jdbc.Driver
public class JDBCUtils {
//关闭资源
public static void closeResource(Connection conn, PreparedStatement pps){
try {
if(pps!=null){
pps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 通过druid连接池获取连接
* @Param []
* @return java.sql.Connection
**/
public static Connection getDruidConnection(){
Properties ps = new Properties();
Connection conn = null;
try {
FileInputStream fs = new FileInputStream(new File("druid.properties"));
ps.load(fs);
DataSource ds = DruidDataSourceFactory.createDataSource(ps);
conn = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
/**
* @Description TODO
* @Author YunShuaiWei
* @Date 2020/6/23 10:19
* @Version
**/
public class dbUtilsTest {
//插入测试
@Test
public void insertTest() {
Connection conn = null;
int i = 0;
try {
QueryRunner runner = new QueryRunner();
conn = JDBCUtils.getDruidConnection();
String sql = "insert into account(name,money)values(?,?)";
i = runner.update(conn, sql, "yunsw", "1000");
System.out.println("成功添加了 " + i + " 条记录!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, null);
}
}
//查询测试
@Test
public void testQuery() {
QueryRunner runn = new QueryRunner();
Connection conn = JDBCUtils.getDruidConnection();
String sql = "select * from account where id=?";
BeanHandler<AccountDAO> handler = new BeanHandler<>(AccountDAO.class);
AccountDAO query = null;
try {
query = runn.query(conn, sql, handler, 7);
System.out.println(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, null);
}
}
//查询多条记录:BeanListHandler
@Test
public void testQueryBeanListHandler() {
QueryRunner runner = new QueryRunner();
Connection conn = JDBCUtils.getDruidConnection();
String sql = "select id,name,money from account where money";
BeanListHandler handler = new BeanListHandler(AccountDAO.class);
try {
List<AccountDAO> list = (List<AccountDAO>) runner.query(conn, sql, handler, 10000);
list.forEach(System.out::println);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, null);
}
}
//查询特殊值
@Test
public void countTestScalarHandler() {
Connection conn = null;
try {
QueryRunner runner = new QueryRunner();
conn = JDBCUtils.getDruidConnection();
String sql = "select Max(money) from account";
ScalarHandler handler = new ScalarHandler();
Double query = (Double) runner.query(conn, sql, handler);
System.out.println(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, null);
}
}
}