//Author 流云
//Version 1.0
Class.forName("com.mysql.jdbc.Driver");//加载驱动
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/database?
useUnicode=true&characterEncoding=utf8", "root","1234");
Statement statement = conn.createStatement();
String sql ="INSERT INTO t_jobs(JOB_ID,JOB_TITLE,MIN_SALARY,MAX_SALARY)
VALUES('JAVA_Le','JAVA_Lecturer',4000,10000);";
int result = statement.executeUpdate(sql);//执行SQL语句并接收结果
if(result == 1){
System.out.println("Success");
}
statement.close();
conn.close();
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DeleteJdbc {
public static void main(String[] args) throws Exception{
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb","root","1234");
//3.获得执行SQL的对象
Statement statement = connection.createStatement();
//4.执行SQL语句,并接收结果
int result = statement.executeUpdate("delete from t_jobs where job_id = 'H5_mgr';");
//5.处理结果
if(result==1){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
//6.释放资源
statement.close();
connection.close();
}
}
ResultSet rs= statement.executeQuery("SELECT * FROM t_employees;");
boolean next() throws SQLException //判断 rs 结果集中下一行是否存在数据
int getInt(int columnIndex) throws SQLException //获得当前行第N列的int值
int getInt(String columnLabel) throws SQLException //获得当前行columnLabel列的int值
double getDouble(int columnIndex) throws SQLException //获得当前行第N列的double值
double getDouble(String columnLabel) throws SQLException //获得当前行columnLabel列的double值
String getString(int columnIndex) throws SQLException //获得当前行第N列的String值
String getString(String columnLabel) throws SQLException //获得当前行columnLabel列的String值
......
package com.www.test;
import java.sql.*;
public class JobsQuery {
public static void main(String[] args) {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/product", "root", "1234");
//3.获取发送 sql 语句对象
Statement statement = connection.createStatement();
//4.执行 SQL 语句并接收结果集
ResultSet resultSet = statement.executeQuery("select * from t_jobs");
//5 处理结果集
while(resultSet.next()){
//5.1有数据,依据列名获取数据
String job_id = resultSet.getString("job_id");
String job_title = resultSet.getString("job_title");
int min_salary = resultSet.getInt("min_salary");
int max_salary = resultSet.getInt("max_salary");
System.out.println(job_id+"\t"+job_title+"\t"+min_salary+"\t"+max_salary);
}
//6.释放资源
rs.close();
statement.close();
connection.close();
}
}
//。。。。与上无异
while(resultSet.next()){
//5.2有数据,依据列名获取数据
String job_id = resultSet.getString(1);
String job_title = resultSet.getString(2);
int min_salary = resultSet.getInt(3);
int max_salary = resultSet.getInt(4);
System.out.println(job_id+"\t"+job_title+"\t"+min_salary+"\t"+max_salary);
}
//释放资源
//1.预编译 SQL 语句
PreparedStatement pstmt = conn.prepareStatement("select * from user where username=? and password=?");
//1.预编译 SQL 语句
PreparedStatement pstmt = conn.prepareStatement("select * from user where username=? and password=?");
//2.为参数下标赋值
pstmt.setString(1,username);
pstmt.setString(2,password);
package com.jdbc;
import java.sql.*;
/**
* 重用性方案
* 获取连接
* 释放资源
*/
public class DBUtils {
static {//类加载,执行一次!
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//1.获取连接
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/companydb", "root","1234");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//2.释放资源
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb3
user=root
password=123456
package com.jdbc2;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtils {
private static final Properties PROPERTIES = new Properties();//存储配置文件的map
static {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
try {
PROPERTIES.load(is);//通过流,将配置文件内容加载到properties集合
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(PROPERTIES.getProperty("url"),
PROPERTIES.getProperty("username"), PROPERTIES.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.www.test;
public class T_Jobs {
private String job_id;
private String job_title;
private int min_salary;
private int max_salary;
@Override
public String toString() {
return "T_Jobs{" +
"job_id='" + job_id + '\'' +
", job_title='" + job_title + '\'' +
", min_salary=" + min_salary +
", max_salary=" + max_salary +
'}';
}
public String getJob_id() {
return job_id;
}
public void setJob_id(String job_id) {
this.job_id = job_id;
}
public String getJob_title() {
return job_title;
}
public void setJob_title(String job_title) {
this.job_title = job_title;
}
public int getMin_salary() {
return min_salary;
}
public void setMin_salary(int min_salary) {
this.min_salary = min_salary;
}
public int getMax_salary() {
return max_salary;
}
public void setMax_salary(int max_salary) {
this.max_salary = max_salary;
}
public T_Jobs() {
}
public T_Jobs(String job_id, String job_title, int min_salary, int max_salary) {
this.job_id = job_id;
this.job_title = job_title;
this.min_salary = min_salary;
this.max_salary = max_salary;
}
}
package com.www.test;
import java.sql.*;
public class JobsQuery {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String URL = "jdbc:mysql://localhost:3306/product";
String user = "root";
String password = "1234";
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
connection = DriverManager.getConnection(URL, user, password);
//3.编写 SQL 语句
String sql = "select * from t_jobs";
//4.获取发送 sql 语句对象
statement = connection.createStatement();
//5.执行 SQL 语句并接收结果集
resultSet = statement.executeQuery(sql);
//5.1使用 while 循环判断下一行是否有数据
while(resultSet.next()){
//5.2有数据,依据列名获取数据
String job_id = resultSet.getString(1);
String job_title = resultSet.getString(2);
int min_salary = resultSet.getInt(3);
int max_salary = resultSet.getInt(4);
//5.3 创建实体类对象
T_Jobs t_jobs = new T_Jobs();
//5.4 每列数据对应属性进行赋值
t_jobs.setJob_id(job_id);
t_jobs.setJob_title(job_title);
t_jobs.setMin_salary(min_salary);
t_jobs.setMax_salary(max_salary);
System.out.println(t_jobs);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
//6.释放资源
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.person;
import sun.awt.image.DataBufferNative;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 增、删、改、查单个、查所有
* 只做数据库访问操作!不参与逻辑判断
* 数据库一张表的访问的操作复用!
*/
public class PersonDaoImpl {
//新增
public int insert(Person person){
Connection connection = null;
PreparedStatement preparedStatement = null;
String sql = "insert into person(name,age,borndate,email,address) values(?,?,?,?,?);";
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,person.getName());
preparedStatement.setInt(2,person.getAge());
preparedStatement.setDate(3,null);
preparedStatement.setString(4,person.getEmail());
preparedStatement.setString(5,person.getAddress());
int result = preparedStatement.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(connection,preparedStatement,null);
}
return 0;
}
//修改
public int update(Person person){
Connection connection =null;
PreparedStatement preparedStatement = null;
String sql = "update person set
name=?,age=?,borndate=?,email=?,address=? where id = ?";
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,person.getName());
preparedStatement.setInt(2,person.getAge());
preparedStatement.setDate(3,null);
preparedStatement.setString(4,person.getEmail());
preparedStatement.setString(5,person.getAddress());
preparedStatement.setInt(6,person.getId());
int result = preparedStatement.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(connection,preparedStatement,null);
}
return 0;
}
//删除
public int delete(int id){
Connection connection = null;
PreparedStatement preparedStatement = null;
String sql = "delete from person where id= ?;";
connection = DBUtils.getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,id);
int result = preparedStatement.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(connection,preparedStatement,null);
}
return 0;
}
//查单个
public Person select(int id){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "select * from person where id = ?;";
Person person = null;
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,id);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
person = new Person();
int pid= resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date bornDate = resultSet.getDate("borndate");
String email = resultSet.getString("email");
String address = resultSet.getString("address");
person.setId(pid);
person.setName(name);
person.setAge(age);
person.setBornDate(bornDate);
person.setEmail(email);
person.setAddress(address);
}
return person;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(connection,preparedStatement,resultSet);
}
return null;
}
//查所有
public List selectAll(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Person person = null;
List personList = new ArrayList<>();
try {
connection = DBUtils.getConnection();
preparedStatement = connection.prepareStatement("select * from person;");
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
int pid= resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date bornDate = resultSet.getDate("borndate");
String email = resultSet.getString("email");
String address = resultSet.getString("address");
person = new Person(pid,name,age,bornDate,email,address);
personList.add(person);
}
return personList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* 将所有数据表的操作,抽离成一个公用的方法;
* @Param sql 语句
* @Param sql语句对应的参数
* @return
*/
public static boolean executeDML(String sql,Object... params){
try {
//获取连接
Connection connection = getConnection();
//获取预处理的对象
PreparedStatement ps = connection.prepareStatement(sql);
//设置参数
if(null != params){
for(int i = 0 ; i < params.length ; i++){
//1:给占位符设置参数;2:获取参数
ps.setObject(i+1,params[i]);
}
}
int i = ps.executeUpdate();
close(null,ps,connection);
return i > 0;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return false;
}
/**
* 通用的查询;需要将我们的数据表信息,封装到List里面进行返回
* @param sql 查询语句
* @param cls 实体类的字节码对象
* @param params 查询语句里面的占位符
* @param 实体类类型泛型
* @return 就是我们查询到的数据集合
*/
public static List executeDQL(String sql, Class cls , Object...params) {
try {
Connection connection = getConnection(); //获取连接
//获取预处理sql
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//设置参数
if(null != params){
for(int i = 0 ; i < params.length ; i++){
preparedStatement.setObject(i+1,params[i]);
}
}
//执行查询 得到结果集
ResultSet resultSet = preparedStatement.executeQuery();
//获取元数据(我们的列名)
ResultSetMetaData metaData = resultSet.getMetaData();
//列的总数
int columnCount = metaData.getColumnCount();
//用来保存我们所有的表数据
List list = new ArrayList();
T t;//用来保存我们一条数据
//遍历结果集
while(resultSet.next()){ //每一行记录的遍历过程中
t = cls.newInstance();//根据字节码文件,构建一个实体类的对象
//获取所有列的数据
for(int i = 1 ; i <= columnCount ; i++){
//你的查询语句有时候有别名
String columnLabel = metaData.getColumnLabel(i);
//根据列名获取我们的记录
Object object = resultSet.getObject(columnLabel);
//需要将拿到的这一列的记录,放到t对象指定的属性里面;
//需要拿到这个t对象的属性,然后赋值;
//解决方案2: 如果Object是NULL没有必要设置了
if(null != object){
try {
Field field = cls.getDeclaredField(columnLabel);//根据属性的名称通过反射获取他的属性对象
field.setAccessible(true);
field.set(t,object);
} catch (NoSuchFieldException e) {
//代表我们当前这个实体类里面,没有这个属性
}
}
}
//需要将t对象保存到list
list.add(t);
}
close(resultSet,preparedStatement,connection);
return list;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
package com.project.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 连接池工具类
*/
public class DBUtils {
private static DruidDataSource dataSource;
static {
Properties properties = new Properties();
InputStream is = DBUtils.class.getResourceAsStream("/database.properties");
try {
properties.load(is);
dataSource = (DruidDataSource)
DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 返回一个数据源
public static DataSource getDataSource(){
return dataSource;
}
}
package com.project.dao.impl;
import com.project.dao.UserDao;
import com.project.entity.User;
import com.project.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class UserDaoImpl implements UserDao {
//1.创建QueryRunner对象,并传递一个数据源对象
private QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
@Override
public int insert(User user) {
Object[] params={user.getId(),user.getUsername(),user.getPassword(),user.getSex(),user.getEmail(),user.getAddress()};
try {
return queryRunner.update("insert into user(id,username,password,sex,email,address) values(?,?,?,?,?,?)",params);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int update(User user) {
Object[] params={user.getUsername(),user.getPassword(),user.getSex(),user.getEmail(),user.getAdd ress(),user.getId()};
try {
return queryRunner.update("update user set
username=?,password=?,sex=?,email=?,address=? where id = ?",params);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delete(int id) {
try {
return queryRunner.update("delete from user where id = ?",id);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public User select(int id) {
try {
//把查询到的记录封装成 指定对象
return queryRunner.query("select * from user where id = ?", new
BeanHandler(User.class), id);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 查询所有
* @return
*/
@Override
public List selectAll() {
try {
return queryRunner.query("select * from user;",new
BeanListHandler(User.class));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mytest
username=root
password=123456
#
initialSize=10
#最大连接数量
maxActive=50
#
minIdle=5
#
maxWait=5000
public class DbUtils {
//声明连接池对象
private static DruidDataSource ds;
static{
//实例化配置对象
Properties properties=new Properties();
try {
//加载配置文件内容
properties.load(DbUtils.class.getResourceAsStream("druid.properties"));
ds = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取连接对象
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//释放资源。。
}
/*
一、主要配置
1、dataSourceClassName
这是DataSourceJDBC驱动程序提供的类的名称。请注意,如果您正在使用jdbcUrl“旧式”基于DriverManager的JDBC驱动程序配置,则不需要此属性 。 默认值:无
2、jdbcUrl
请注意,如果使用此属性,您仍然可以使用DataSource属性来配置您的驱动程序,实际上建议您使用URL本身中指定的驱动程序参数。 默认值:无
3、username
此属性设置从基础驱动程序获取连接时使用的默认身份验证用户名。
4、password
此属性设置从基础驱动程序获取连接时使用的默认身份验证密码。
*/
public static void main(String[] args) throws SQLException {
HikariConfig hikariConfig = new HikariConfig();
//设置url
hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/mytest?characterEncoding=UTF-8");
//数据库帐号
hikariConfig.setUsername("root");
//数据库密码
hikariConfig.setPassword("123456");
HikariDataSource ds = new HikariDataSource(hikariConfig);
}
//如果保存1w条记录
String sql = "insert into userinfo(uname,upass) values(?,?)";
Connection connection = DBUtilPool.getConnectionByDruid();
long start = System.currentTimeMillis();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for(int i = 0 ; i < 10000 ; i++){
preparedStatement.setObject(1,"jack"+i);
preparedStatement.setObject(2,"aaaa"+i);
preparedStatement.addBatch(); //将当前的sql预编译好以后,加到批处理; 不会直接执行到数据库里面
if(i % 500 == 0){
preparedStatement.executeBatch(); //执行我们批处理
preparedStatement.clearBatch(); //把上面的执行了,需要清空
}
}
preparedStatement.executeBatch(); //最后一次进行批处理
long end = System.currentTimeMillis();
System.out.println("");
System.out.println(end-start);
BEGIN ;-- 代表我们开启了一个事务
UPDATE user_acount SET umoney = umoney-200 WHERE uname = 'jack';
-- 断网了 断电了
UPDATE user_acount SET umoney = umoney+200 WHERE uname = 'rose';
ROLLBACK -- 回滚事务(代表整个事务执行失败)
COMMIT; -- 提交事务
-- 默认提交事务
begin;
commit; -- 提交事务
rollback; -- 事务回滚
//代码里面默认回滚事务
connection.setAutoCommit(false); //不自动提交事务
connection.commit();//提交事务
connection.rollback();//回滚事务