为了让开发人员对数据库的统一操作,提供了一个java操作数据库的规范。
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;
CREATE TABLE `users`(
id INT PRIMARY KEY,
NAME VARCHAR(40),
PASSWORD VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO `users`(id,NAME,PASSWORD,email,birthday)
VALUES(1,‘zhansan‘,‘123456‘,‘zs@sina.com‘,‘1980-12-04‘),
(2,‘lisi‘,‘123456‘,‘lisi@sina.com‘,‘1981-12-04‘),
(3,‘wangwu‘,‘123456‘,‘wangwu@sina.com‘,‘1979-12-04‘)
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动
//2.用户信息和url
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password ="root123";
//3.连接成功
Connection connection = DriverManager.getConnection(url, username, password);
//4.执行sql的对象 statement执行sql的对象
Statement statement = connection.createStatement();
//5.执行sql的对象去执行sql,可能存在结果,查看返回结果
String sql ="select * from users";
ResultSet resultSet = statement.executeQuery(sql); //返回结果集,结果存在所有的结果
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("pwd="+resultSet.getObject("password"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birthday="+resultSet.getObject("birthday"));
System.out.println("=================================");
}
//6.释放连接(一定要关闭)
resultSet.close();
statement.close();
connection.close();
}
//第一种写法
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//第二种写法推荐写法
Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动
//连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//提交
connection.commit();
//设置事务true或false
connection.setAutoCommit(false);
//回滚
connection.rollback();
mysql
驱动:com.mysql.jdbc.Driver
URL:jdbc:mysql://127.0.0.1:port/dbname
注:127.0.0.1:数据库所在机器的名称
port:端口号,默认是3306
dbname:数据库名称
oracle
驱动:oracle.jdbc.driver.OracleDriver
URL:jdbc:oracle:thin:127.0.0.1:port:dbname
注:127.0.0.1:数据库所在机器的名称
port:端口号,默认是1521
dbname:数据库名称
String sql ="select * from users"; //编写sql
statement.executeQuery()//查询
statement.execute()//执行任何sql
statement.executeUpdate()//增删改数据都是用这个
statement.executeBatch()//执行多条sql
//不知道列类型使用
resultSet.getObject();
//如果知道列类型用以下函数
resultSet.getString();
resultSet.getInt();
resultSet.getDouble();
resultSet.getFloat();
resultSet.getDate();
遍历,指针
resultSet.beforeFirst();//移动到最前面
resultSet.afterLast();//移动到最后面
resultSet.next();//移动到下一个
resultSet.previous();//移动到前一行
resultSet.absolute();//移动到指定行
1.8释放资源
//必须释放(占用资源大)顺序resultSet>>statement>>connection
resultSet.close();
statement.close();
connection.close();
提取工具类
//db.properties
driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username = root
password =root123
//jdbcUtils.java
import java.io.*;
import java.sql.*;
import java.util.*;
public class jdbcUtils {
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
static {
try {
InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1.驱动只加载异常
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
//释放连接
public static void release(Connection connection,Statement statement,ResultSet resultSet){
if (resultSet !=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement !=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}if (connection !=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
增加数据
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.*;
public class TestUtilAdd {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="INSERT INTO users(name,password,email,birthday) VALUES(‘zhangsan‘,‘1253348‘,‘11222243464@qq.com‘,‘2021-3-18‘)";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
更改数据
package xiaozhi.jd1;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtilUpdate {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="UPDATE users SET NAME=‘李五‘ WHERE name =‘zhangsahn‘ ";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("更新成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
删除数据
package xiaozhi.jd1;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtilDel {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="DELETE FROM users WHERE NAME=‘李五‘";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("删除成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
package xiaozhi.jd1;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtilSelect {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="select * from users where id=2";
rs = st.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("pwd="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
System.out.println("=================================");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
mysql存在的问题,会导致数据泄露
package xiaozhi.jd1;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtilLogin {
public static void main(String[] args) {
// login("wangwu","123456");
//sql注入
login("‘or ‘1=1","123456");
}
public static void login(String username,String pwd){
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="select * from users WHERE name = ‘"+username+"‘and password =‘"+pwd+"‘";
rs = st.executeQuery(sql);
if (rs.next()){
System.out.println("登录成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
该对象可以防止sql注入,效率更好
1.91新增
package xiaozhi.PreparedStatementDemo;
import xiaozhi.jd1.utils.jdbcUtils;
import java.util.Date;
import java.sql.*;
import java.sql.PreparedStatement;
public class TestInsert{
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
//插入语句 用?做占位符
String sql ="insert into users(name,password,email,birthday) value(?,?,?,?)";
st = conn.prepareStatement(sql);//预编译sql,先写sql,不执行
//手动赋值
st.setString(1,"xiaoou");
st.setString(2,"5223556");
st.setString(3,"522365122@qq.com");
st.setDate(4,new java.sql.Date(new Date().getTime()));
//执行 不需要再写入sql
int i = st.executeUpdate();
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
1.92更新
package xiaozhi.PreparedStatementDemo;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class TestUpdate {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
//插入语句 用?做占位符
String sql ="update users set name = ? where name=?";
st = conn.prepareStatement(sql);//预编译sql,先写sql,不执行
//手动赋值
st.setString(1,"xiaozhi");
st.setString(2,"xiaoou");
//执行 不需要再写入sql
int i = st.executeUpdate();
if (i>0){
System.out.println("修改成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
1.93删除
package xiaozhi.PreparedStatementDemo;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestDelete {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
//插入语句 用?做占位符
String sql ="delete from users where name = ?";
st = conn.prepareStatement(sql);//预编译sql,先写sql,不执行
//手动赋值
st.setString(1,"xiaozhi");
//执行 不需要再写入sql
int i = st.executeUpdate();
if (i>0){
System.out.println("删除成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
1.94查询
package xiaozhi.PreparedStatementDemo;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestSelect {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
//插入语句 用?做占位符
String sql ="select * from users WHERE NAME = ?";
st = conn.prepareStatement(sql);//预编译sql,先写sql,不执行
//手动赋值
st.setString(1,"zhansan");
//执行 不需要再写入sql
rs= st.executeQuery();
if (rs.next()){
System.out.println("查询成功"+rs.getString("name"));
System.out.println("==============");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
1.95sql注入测试
package xiaozhi.PreparedStatementDemo;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.*;
public class TestUtilLogin {
public static void main(String[] args) {
// login("wangwu","123456");
// //sql注入
login("‘or ‘1=1","123456");
}
public static void login(String username,String pwd){
Connection conn =null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
//插入语句
String sql ="select * from users WHERE name = ? and password =?";
st = conn.prepareStatement(sql);//获取执行对象 先转义字符
st.setString(1,username);
st.setString(2,pwd);
rs = st.executeQuery();
if (rs.next()){
System.out.println("登录成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
serverTimezone设置为CST
GMT(Greenwich Mean Time):格林威治标准时间
UTC:世界标准时间
CST(China Standard Time):中国标准时间
GMT + 8 = UTC + 8 = CST
要么都成功,要么都失败
原子性:要么全部完成,要么都不完成
一致性:总数不变
隔离性:多个进程互不干扰
持久性:一旦提交不可逆,持久化到数据库
隔离性的问题:
脏读:一个事务读取了另一个没有提交的事务
不可重复读:在同一个事务内,重复读取表中的数据,表数据发生了改变
虚读(幻读):在一个事务内,读取到了别人插入的数据,导致前后读出来结果不一致
package xiaozhi.transactionDemo;
import xiaozhi.jd1.utils.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class Tdemo2 {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st = null;
PreparedStatement st1 = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();//获取连接
//关闭数据库的自动提交,自动会开启事务注意是InnoDB
conn.setAutoCommit(false);//开启事务
//插入语句 用?做占位符
String sql ="update account set money = money-500 where name=?";
st = conn.prepareStatement(sql);//预编译sql,先写sql,不执行
st.setString(1, "A");
st.executeUpdate();
int x=1/0;
String sql1 ="update account set money = money+500 where name=?";
st1 = conn.prepareStatement(sql1);//预编译sql,先写sql,不执行
//手动赋值
st1.setString(1, "B");
//执行 不需要再写入sql
st1.executeUpdate();
} catch (Exception e) {
// 回滚事务:
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
jdbcUtils.release(conn,st,rs);
}
}
}
架包
dbcpconfig.properties
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=root123
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
jdbc_Utils
package xiaozhi.JdbcDemo.utils;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class jdbc_Utils {
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
private static DataSource dataSource=null;
static {
try {
InputStream in = jdbc_Utils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(in);
//创建数据源
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();//从数据源中获取
}
//释放连接
public static void release(Connection connection,Statement statement,ResultSet resultSet){
if (resultSet !=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement !=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}if (connection !=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
test
package xiaozhi.JdbcDemo.test;
import xiaozhi.JdbcDemo.utils.jdbc_Utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtilAdd {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbc_Utils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="INSERT INTO users(name,password,email,birthday) VALUES(‘zhangsan‘,‘1253348‘,‘11222243464@qq.com‘,‘2021-3-18‘)";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbc_Utils.release(conn,st,rs);
}
}
}
架包
c3p0-config.xml
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true</property>
<property name="user">root</property>
<property name="password">root123</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!-- This app is massive! -->
<named-config name="intergalactoApp">
<property name="acquireIncrement">50</property>
<property name="initialPoolSize">100</property>
<property name="minPoolSize">50</property>
<property name="maxPoolSize">1000</property>
<!-- intergalactoApp adopts a different approach to configuring statement caching -->
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>
<!-- he‘s important, but there‘s only one of him -->
<user-overrides user="master-of-the-universe">
<property name="acquireIncrement">1</property>
<property name="initialPoolSize">1</property>
<property name="minPoolSize">1</property>
<property name="maxPoolSize">5</property>
<property name="maxStatementsPerConnection">50</property>
</user-overrides>
</named-config>
</c3p0-config>
jdbc_Utils
package xiaozhi.c3p0Demo.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class jdbc_Utils {
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
private static DataSource dataSource=null;
private static ComboPooledDataSource comboPooledDataSource=null;
static {
try {
InputStream in = jdbc_Utils.class.getClassLoader().getResourceAsStream("c3p0-config.xml");
Properties properties = new Properties();
properties.load(in);
//创建数据源
// dataSource = BasicDataSourceFactory.createDataSource(properties);
comboPooledDataSource = new ComboPooledDataSource();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return comboPooledDataSource.getConnection();//从数据源中获取
}
//释放连接
public static void release(Connection connection,Statement statement,ResultSet resultSet){
if (resultSet !=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement !=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}if (connection !=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
test
package xiaozhi.c3p0Demo.test;
import xiaozhi.c3p0Demo.utils.jdbc_Utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUtilAdd {
public static void main(String[] args) {
Connection conn =null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbc_Utils.getConnection();//获取连接
st = conn.createStatement();//获取执行对象
//插入语句
String sql ="INSERT INTO users(name,password,email,birthday) VALUES(‘zhangsan‘,‘1253348‘,‘11222243464@qq.com‘,‘2021-3-18‘)";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbc_Utils.release(conn,st,rs);
}
}
}
原文:https://www.cnblogs.com/xiaozhizxj/p/15195386.html