热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

[Java基础]—JDBC

前言其实学Mybatis前就该学了,但是寻思目前主流框架都是用mybatis和mybatis-plus就没再去看,结果在代码审计中遇到了很多cms是使


前言

其实学Mybatis前就该学了,但是寻思目前主流框架都是用mybatis和mybatis-plus就没再去看,结果在代码审计中遇到了很多cms是使用jdbc的因此还是再学一下吧。

第一个JDBC程序

sql文件

INSERT INTO `users`(`id`, `NAME`, `PASSWORD`, `email`, `birthday`) VALUES (1, 'zhansan', '123456', 'zs@sina.com', '1980-12-04');
INSERT INTO `users`(`id`, `NAME`, `PASSWORD`, `email`, `birthday`) VALUES (2, 'lisi', '123456', 'lisi@sina.com', '1981-12-04');
INSERT INTO `users`(`id`, `NAME`, `PASSWORD`, `email`, `birthday`) VALUES (3, 'wangwu', '123456', 'wangwu@sina.com', '1979-12-04');

HelloJDBC

import java.sql.*;
public class HelloJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2. 用户信息和url
String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true";
String name = "root";
String password = "123456";
//3. 连接数据库 connection是数据库对象
Connection connection = DriverManager.getConnection(url, name, password);
//4. 执行sql的对象 statement是执行sql的对象
Statement statement = connection.createStatement();
//5. 用statement对象执行sql语句
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id:"+resultSet.getObject("id")+",name:"+resultSet.getObject("name")+",password:"+resultSet.getObject("password"));
System.out.println("=============================");
}
//6.释放资源
resultSet.close();
statement.close();
connection.close();
}
}

Statement对象

工具类

package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
public static Connection connection() throws ClassNotFoundException, SQLException, IOException {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class.forName(driver);
return DriverManager.getConnection(url,username,password);
}
public static void relese(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
}
}

Demo

import utils.JdbcUtils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcStatement {
public static void main(String[] args) throws Exception {
// query();
insert();
}
public static void query() throws SQLException, ClassNotFoundException, IOException{
Connection connection = JdbcUtils.connection();
String sql = "select * from users";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id:"+resultSet.getObject("id"));
}
JdbcUtils.relese(resultSet,statement,connection);
}
public static void insert() throws Exception{
Connection connection = JdbcUtils.connection();
String sql = "insert into users values(4,'Sentiment',123456,'Sentiment@qq.com','1980-12-04')";
Statement statement = connection.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
JdbcUtils.relese(null,statement,connection);
}
}

查询用executeQuery(),增、删、改用executeUpdate()

PreparedStatement对象

用statement的话会有sql注入问题,因此可以用preparedstatement进行预处理来进行防御

主要是通过占位符来执行查询语句

public class JdbcPreparedStatement {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
Connection connection = JdbcUtils.connection();
String sql = "insert into users values(?,?,?,null,null)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1,5);
ps.setString(2,"Sentiment");
ps.setInt(3,123456);
ps.execute();
}
}

操作事务

mybatis中学过,不过连含义都忘了。。。。

其实就是执行语句时要不都成功执行,一个不能执行则全部都不执行

主要就是关闭自动提交事务

connection.setAutoCommit(false); //开启事务

Demo

PreparedStatement ps = null;
Connection connection = null;
try {
connection = JdbcUtils.connection();
//关闭数烟库的自动提交,自动会开启事务connection
connection.setAutoCommit(false); //开启事务
String sql1 = "update users set name = 'Sentiment' where id=3";
ps = connection.prepareStatement(sql1);
ps.executeUpdate();
int x = 1 / 0;
String sql2 = "update users set name = 'Sentiment' where id=1";
ps = connection.prepareStatement(sql2);
ps.executeUpdate();
connection.commit();
System.out.println("Success!");
}catch (SQLException e){
connection.rollback(); //执行失败后,事务回滚
}finally {
JdbcUtils.relese(null,ps,connection);
}
}

数据库连接池

在上述工具类中,是通过以下方法来获取配置文件参数,并连接连接池

String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class.forName(driver);
return DriverManager.getConnection(url,username,password);

而我们可以用开源的数据库连接池如DBCP、C3P0、Druid等

使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码了!

DBCP


commons-dbcp
commons-dbcp
1.4


commons-pool
commons-pool
1.5.4

配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456
#<!-- 初始化连接 -->
initialSize&#61;10
#最大连接数量
maxActive&#61;50
#<!-- 最大空闲连接 -->
maxIdle&#61;20
#<!-- 最小空闲连接 -->
minIdle&#61;5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60-->
maxWait&#61;60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样&#xff1a;【属性名&#61;property;
#注意&#xff1a;"user""password" 两个属性会被明确地传递&#xff0c;因此这里不需要包含他们。
connectionProperties&#61;useUnicode&#61;true;characterEncoding&#61;utf8
#指定由连接池所创建的连接的自动提交&#xff08;auto-commit&#xff09;状态。
defaultAutoCommit&#61;true
#driver default 指定由连接池所创建的连接的只读&#xff08;read-only&#xff09;状态。
#如果没有设置该值&#xff0c;则“setReadOnly”方法将不被调用。&#xff08;某些驱动并不支持只读模式&#xff0c;如&#xff1a;Informix&#xff09;
defaultReadOnly&#61;true
#driver default 指定由连接池所创建的连接的事务级别&#xff08;TransactionIsolation&#xff09;。
#可用值为下列之一&#xff1a;&#xff08;详情可见javadoc。&#xff09;NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation&#61;READ_COMMITTED

Demo

使用DBCP后&#xff0c;utils就可以简化为&#xff1a;

public static Connection connection() throws Exception {
InputStream in &#61; DBCP_Utils.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties &#61; new Properties();
properties.load(in);
//创建数据源
DataSource dataSource &#61; BasicDataSourceFactory.createDataSource(properties);
return dataSource.getConnection();
}

读取配置文件&#xff0c;交给数据源即可

C3P0

这个更简单

<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.5version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>mchange-commons-javaartifactId>
<version>0.2.19version>
dependency>

配置文件

这里设置了两个数据源&#xff1a;

:默认值创建数据源时不需要形参&#xff0c;ComboPooledDataSource ds&#61;new ComboPooledDataSource();

: 非默认要指定数据源&#xff0c;ComboPooledDataSource ds&#61;new ComboPooledDataSource(“MySQL”);

<?xml version&#61;"1.0" encoding&#61;"UTF-8"?>
<c3p0-config>
<!--
c3p0的缺省&#xff08;默认&#xff09;配置
如果在代码中"ComboPooledDataSource ds&#61;new ComboPooledDataSource();"这样写就表示使用的是c3p0的缺省&#xff08;默认&#xff09;
-->
<default-config>
<property name&#61;"driverClass">com.mysql.jdbc.Driver</property>
<property name&#61;"jdbcUrl">jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode&#61;true&amp;characterEncoding&#61;utf8&amp;useSSL&#61;true</property>
<property name&#61;"user">root</property>
<property name&#61;"password">123456</property>
<property name&#61;"acquiredIncrement">5</property>
<property name&#61;"initialPoolSize">10</property>
<property name&#61;"minPoolSize">5</property>
<property name&#61;"maxPoolSize">20</property>
</default-config>
<!--
c3p0的命名配置
如果在代码中"ComboPooledDataSource ds&#61;new ComboPooledDataSource("MySQL");"这样写就表示使用的是mysql的缺省&#xff08;默认&#xff09;
-->
<named-config name&#61;"MySQL">
<property name&#61;"driverClass">com.mysql.jdbc.Driver</property>
<property name&#61;"jdbcUrl">jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode&#61;true&amp;characterEncoding&#61;utf8&amp;useSSL&#61;true</property>
<property name&#61;"user">root</property>
<property name&#61;"password">123456</property>
<property name&#61;"acquiredIncrement">5</property>
<property name&#61;"initialPoolSize">10</property>
<property name&#61;"minPoolSize">5</property>
<property name&#61;"maxPoolSize">20</property>
</named-config>
</c3p0-config>

Demo

xml文件默认能读取到

public static Connection connection() throws Exception {
ComboPooledDataSource dataSource&#61;new ComboPooledDataSource();
return dataSource.getConnection();
}

自带日志

在这里插入图片描述






推荐阅读
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • Java String与StringBuffer的区别及其应用场景
    本文主要介绍了Java中String和StringBuffer的区别,String是不可变的,而StringBuffer是可变的。StringBuffer在进行字符串处理时不生成新的对象,内存使用上要优于String类。因此,在需要频繁对字符串进行修改的情况下,使用StringBuffer更加适合。同时,文章还介绍了String和StringBuffer的应用场景。 ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • Ihavethefollowingonhtml我在html上有以下内容<html><head><scriptsrc..3003_Tes ... [详细]
  • Python SQLAlchemy库的使用方法详解
    本文详细介绍了Python中使用SQLAlchemy库的方法。首先对SQLAlchemy进行了简介,包括其定义、适用的数据库类型等。然后讨论了SQLAlchemy提供的两种主要使用模式,即SQL表达式语言和ORM。针对不同的需求,给出了选择哪种模式的建议。最后,介绍了连接数据库的方法,包括创建SQLAlchemy引擎和执行SQL语句的接口。 ... [详细]
  • Java学习笔记之使用反射+泛型构建通用DAO
    本文介绍了使用反射和泛型构建通用DAO的方法,通过减少代码冗余度来提高开发效率。通过示例说明了如何使用反射和泛型来实现对不同表的相同操作,从而避免重复编写相似的代码。该方法可以在Java学习中起到较大的帮助作用。 ... [详细]
  • 本文主要复习了数据库的一些知识点,包括环境变量设置、表之间的引用关系等。同时介绍了一些常用的数据库命令及其使用方法,如创建数据库、查看已存在的数据库、切换数据库、创建表等操作。通过本文的学习,可以加深对数据库的理解和应用能力。 ... [详细]
  • 在Oracle11g以前版本中的的DataGuard物理备用数据库,可以以只读的方式打开数据库,但此时MediaRecovery利用日志进行数据同步的过 ... [详细]
author-avatar
阿里根本_436
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有