JDBC
一、软件的架构方式
-
B/S架构:Browser Server 浏览器-服务器 -
C/S架构:Client Server 客户端-服务器 弊端:需要经常更新客户端来访问到最新修改后的信息 优势:有更好的用户体验
二、获取数据库连接
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBC_connection {
@Test
public void connectiontest1() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password","000422");
Connection connection = driver.connect(url,info);
System.out.println(connection);
}
@Test
public void connectionTest2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","000422");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
@Test
public void connectionTest3() throws Exception {
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="000422";
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
@Test
public void connectionTest4() throws Exception{
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="000422";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
@Test
public void ConnectionTest5() throws IOException, ClassNotFoundException, SQLException {
InputStream resource = JDBC_connection.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros=new Properties();
pros.load(resource);
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
三、使用PreparedStatement实现CRUD(增删改查)操作
import com.JDBC.lhk.Connection.JDBC_connection;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class jdbcUtils {
public static Connection getConnection() throws Exception {
InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros=new Properties();
pros.load(resource);
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
public static void closeResource(Connection connection, Statement ps){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void closeResource(Connection connection, Statement ps, ResultSet rs){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (rs!=null)
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static int update(String sql, Object ...args) {
Connection coon = null;
PreparedStatement ps = null;
try {
coon = jdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
jdbcUtils.closeResource(coon,ps);
}
return 0;
}
}
import com.JDBC.lhk.JDBCutil.jdbcUtils;
import org.junit.Test;
import java.io.InputStream;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Properties;
public class PrepareStatementUpdateTest {
@Test
public void insertTest() {
Connection connection = null;
PreparedStatement ps = null;
try {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pos = new Properties();
pos.load(is);
String url = pos.getProperty("url");
String user = pos.getProperty("user");
String password = pos.getProperty("password");
String driverClass = pos.getProperty("driverClass");
Class<?> aClass = Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, password);
String sql="insert into account(username,balance,birth) values(?,?,?)";
ps = connection.prepareStatement(sql);
ps.setString(1,"lhk");
ps.setDouble(2,15800);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
java.util.Date date = simpleDateFormat.parse("2000-04-22");
ps.setDate(3,new Date(date.getTime()));
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
@Test
public void modifyTest() {
Connection coon = null;
PreparedStatement ps = null;
try {
coon = jdbcUtils.getConnection();
String sql="update account set username=?,balance=? where id=3";
ps = coon.prepareStatement(sql);
ps.setString(1,"LHK");
ps.setDouble(2,16800);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
jdbcUtils.closeResource(coon,ps);
}
}
public void update(String sql, Object ...args) {
Connection coon = null;
PreparedStatement ps = null;
try {
coon = jdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
jdbcUtils.closeResource(coon,ps);
}
}
@Test
public void testCommonUpdate(){
String sql="insert into stuinfo(id,name,sex) values(?,?,?)";
update(sql,2,"Themutents","m");
}
}
import com.JDBC.lhk.JDBCutil.jdbcUtils;
import com.JDBC.lhk.bean.Dept2;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class dept2ForQuery {
@Test
public void test(){
String sql="select department_id departmentId,department_name departmentName,manager_id managerId,location_id locationId from dept2 where department_id=?";
Dept2 dept2 = dept2ForQuery(sql, 20);
System.out.println(dept2);
sql="select department_id departmentId,department_name departmentName from dept2 where department_id=?";
Dept2 dept2_1 = dept2ForQuery(sql, 60);
System.out.println(dept2_1);
}
public Dept2 dept2ForQuery(String sql,Object ...args) {
Connection coon = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
coon = jdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()){
Dept2 dept2 = new Dept2();
for (int i=0;i<columnCount;i++){
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = Dept2.class.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(dept2,columnValue);
}
return dept2;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jdbcUtils.closeResource(coon,ps,rs);
}
return null;
}
@Test
public void testQuery() {
Connection coon = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
coon = jdbcUtils.getConnection();
String sql="select * from dept2 where department_id=?";
ps = coon.prepareStatement(sql);
ps.setObject(1,80);
resultSet = ps.executeQuery();
if (resultSet.next()) {
int dept_id = resultSet.getInt(1);
String dept_name = resultSet.getString(2);
int manager_id = resultSet.getInt(3);
int location_id = resultSet.getInt(4);
Dept2 dept2 = new Dept2(dept_id, dept_name, manager_id, location_id);
System.out.println(dept2);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jdbcUtils.closeResource(coon,ps,resultSet);
}
}
}
public class PreparedSatementQuery {
@Test
public void test(){
String sql="select department_id departmentId,department_name departmentName from dept2 where department_id=?";
Dept2 d = query(Dept2.class, sql, 50);
System.out.println(d);
sql="select * from account where id=?";
Account a = query(Account.class, sql, 1);
System.out.println(a);
System.out.println("----------------------------");
sql="select * from account";
List<Account> list1 = getQuery(Account.class, sql);
list1.forEach(System.out::println);
sql="select department_id departmentId,department_name departmentName from dept2 where department_id<?";
List<Dept2> list2 = getQuery(Dept2.class, sql, 100);
list2.forEach(System.out::println);
}
public <T>T query(Class<T> clazz,String sql,Object ...args){
Connection coon = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
coon = jdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()){
T t = clazz.newInstance();
for (int i=0;i<columnCount;i++){
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jdbcUtils.closeResource(coon,ps,rs);
}
return null;
}
public <T> List<T> getQuery(Class<T> clazz, String sql, Object ...args) {
Connection coon = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
coon = jdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
ArrayList<T> list = new ArrayList<>();
while (rs.next()){
T t = clazz.newInstance();
for (int i=0;i<columnCount;i++){
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
jdbcUtils.closeResource(coon,ps,rs);
}
return null;
}
}
四、操作Blob类型数据
如果在指定了相关的Blob类型以后,还报错:xxx too large,那么在mysql的安装目录下,找my.ini文件加上如下的配置参数: max_allowed_packet=16M。同时注意:修改了my.ini文件之后,需要重新启动mysql服务。
import com.JDBC.lhk.JDBCutil.jdbcUtils;
import org.junit.Test;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class BlobTest {
@Test
public void test() {
Connection connection = null;
PreparedStatement ps = null;
FileInputStream is=null;
try {
connection = jdbcUtils.getConnection();
String sql="insert into beauty(name,sex,borndate,phone,photo,boyfriend_id) values(?,?,?,?,?,?) ";
ps = connection.prepareStatement(sql);
ps.setObject(1,"MM");
ps.setObject(2,"f");
ps.setObject(3,"1998-05-06");
ps.setObject(4,"15677775555");
is=new FileInputStream(new File("xc.png"));
ps.setBlob(5,is);
ps.setInt(6,3);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
jdbcUtils.closeResource(connection,ps);
}
}
@Test
public void test1() {
Connection connection = null;
PreparedStatement ps = null;
InputStream is=null;
FileOutputStream fos=null;
try {
connection = jdbcUtils.getConnection();
String sql="select photo from beauty where id=?";
ps = connection.prepareStatement(sql);
ps.setInt(1,27);
ResultSet rs = ps.executeQuery();
if (rs.next()){
is = rs.getAsciiStream("photo");
fos = new FileOutputStream(new File("xiaochou.png"));
int i=0;
byte[] buff=new byte[1024];
while((i= is.read(buff))!=-1){
fos.write(buff,0, i);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
jdbcUtils.closeResource(connection,ps);
}
}
五、批量插入
import com.JDBC.lhk.JDBCutil.jdbcUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class InsertTest {
@Test
public void test1() throws Exception {
long start = System.currentTimeMillis();
Connection connection = jdbcUtils.getConnection();
Statement sm = connection.createStatement();
for (int i=1;i<=20000;i++){
String sql="insert into goods(name) values('name_+"+i+"')";
sm.execute(sql);
}
long end = System.currentTimeMillis();
System.out.println("花费时间:"+(end-start)+"ms");
jdbcUtils.closeResource(connection,sm);
}
@Test
public void test2() throws Exception {
long start = System.currentTimeMillis();
Connection connection = jdbcUtils.getConnection();
String sql="insert into goods(name) values(?)";
PreparedStatement ps = connection.prepareStatement(sql);
for (int i=1;i<=20000;i++){
ps.setString(1,"name_"+i);
ps.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("花费时间:"+(end-start)+"ms");
jdbcUtils.closeResource(connection,ps);
}
@Test
public void test3() {
Connection connection = null;
PreparedStatement ps = null;
try {
long start = System.currentTimeMillis();
connection = jdbcUtils.getConnection();
String sql="insert into goods(name) values(?)";
ps = connection.prepareStatement(sql);
for (int i=1;i<=20000;i++){
ps.setString(1,"name_"+i);
ps.addBatch();
if(i%500==0){
ps.executeBatch();
ps.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println("花费时间:"+(end-start)+"ms");
} catch (Exception e) {
e.printStackTrace();
}
jdbcUtils.closeResource(connection,ps);
}
@Test
public void test4() throws Exception {
long start = System.currentTimeMillis();
Connection connection = jdbcUtils.getConnection();
connection.setAutoCommit(false);
String sql="insert into goods(name) values(?)";
PreparedStatement ps = connection.prepareStatement(sql);
for (int i=1;i<=20000;i++){
ps.setString(1,"name_"+i);
ps.addBatch();
if (i%500==0){
ps.executeBatch();
ps.clearBatch();
}
}
connection.commit();
long end = System.currentTimeMillis();
System.out.println("花费时间:"+(end-start)+"ms");
jdbcUtils.closeResource(connection,ps);
}
}
六、数据库事务
import com.jdbc.lhk.Bean.Account;
import com.jdbc.lhk.utils.JdbcUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
public class TransactionTest {
@Test
public void test(){
String sql="update account set balance=balance-100 where username='?'";
update(sql,"张无忌");
System.out.println(10/0);
String sql2="update account set balance=balance+100 where username='?'";
update(sql2,"赵敏");
System.out.println("转账成功");
}
public int update(String sql, Object ...args) {
Connection coon = null;
PreparedStatement ps = null;
try {
coon = JdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(coon,ps);
}
return 0;
}
@Test
public void test1() {
Connection coon = null;
try {
coon = JdbcUtils.getConnection();
coon.setAutoCommit(false);
String sql="update account set balance=balance-100 where username=?";
update(coon,sql,"张无忌");
System.out.println(10/0);
String sql2="update account set balance=balance+100 where username=?";
update(coon,sql2,"赵敏");
System.out.println("转账成功");
coon.commit();
} catch (Exception e) {
e.printStackTrace();
try {
coon.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} finally {
try {
coon.setAutoCommit(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
JdbcUtils.closeResource(coon,null);
}
}
public int update(Connection coon,String sql, Object ...args) {
PreparedStatement ps = null;
try {
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(null,ps);
}
return 0;
}
@Test
public void test3() throws Exception {
Connection coon= JdbcUtils.getConnection();
System.out.println(coon.getTransactionIsolation());
coon.setAutoCommit(false);
String sql="select id,username,balance from account where id=?";
Account a1 = query(coon, Account.class, sql, 1);
System.out.println(a1);
}
@Test
public void test4() throws Exception {
Connection coon = JdbcUtils.getConnection();
coon.setAutoCommit(false);
String sql="update account set balance=? where id= ?";
update(coon, sql, 1500,1);
Thread.sleep(15000);
System.out.println("修改结束");
}
public <T>T query(Connection coon,Class<T> clazz,String sql,Object ...args){
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()){
T t = clazz.newInstance();
for (int i=0;i<columnCount;i++){
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(null,ps,rs);
}
return null;
}
}
七、DAO及其相关实现类
1.BaseDao
import com.jdbc.lhk.utils.JdbcUtils;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseDao {
public int update(Connection coon, String sql, Object ...args) {
PreparedStatement ps = null;
try {
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(null,ps);
}
return 0;
}
public <T>T query(Connection coon,Class<T> clazz,String sql,Object ...args){
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()){
T t = clazz.newInstance();
for (int i=0;i<columnCount;i++){
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(null,ps,rs);
}
return null;
}
public <T> List<T> getQuery(Connection coon,Class<T> clazz, String sql, Object ...args) {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
ArrayList<T> list = new ArrayList<>();
while (rs.next()){
T t = clazz.newInstance();
for (int i=0;i<columnCount;i++){
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(null,ps,rs);
}
return null;
}
public <E> E getValue(Connection coon,String sql,Object ...args) {
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
if(rs.next()){
return (E) rs.getObject(1);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(null,ps,rs);
}
return null;
}
}
2.实体类
public class Account {
private int id ;
private String username;
private double balance;
public Account() {
}
public Account(int id, String username, double balance) {
this.id = id;
this.username = username;
this.balance = balance;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", balance=" + balance +
'}';
}
}
3.工具类
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
public static Connection getConnection() throws Exception {
InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros=new Properties();
pros.load(resource);
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
public static void closeResource(Connection connection, Statement ps){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void closeResource(Connection connection, Statement ps, ResultSet rs){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (rs!=null)
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static int update(String sql, Object ...args) {
Connection coon = null;
PreparedStatement ps = null;
try {
coon = JdbcUtils.getConnection();
ps = coon.prepareStatement(sql);
for (int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(coon,ps);
}
return 0;
}
}
4.针对于account表的常用操作的接口
import com.jdbc.lhk.Bean.Account;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;
public interface AccountDao {
void insert(Connection coon, Account account);
void deleteById(Connection coon,int id);
void updateById(Connection coon,Account account);
Account getAccountById(Connection coon,int id);
List<Account> getAll(Connection coon);
Long getCount(Connection coon);
}
5.接口实现类
import com.jdbc.lhk.Bean.Account;
import java.sql.Connection;
import java.util.List;
public class AccountDaoImpl extends BaseDao implements AccountDao{
@Override
public void insert(Connection coon, Account account) {
String sql ="insert into account(username,balance) values(?,?)";
update(coon,sql,account.getUsername(),account.getBalance());
}
@Override
public void deleteById(Connection coon, int id) {
String sql="delete from account where id=?";
update(coon,sql,id);
}
@Override
public void updateById(Connection coon, Account account) {
String sql="update account set username=?,balance=? where id=?";
update(coon,sql,account.getUsername(),account.getBalance(),account.getId());
}
@Override
public Account getAccountById(Connection coon, int id) {
String sql="select id,username,balance from account where id=?";
Account query = query(coon, Account.class, sql, id);
return query;
}
@Override
public List<Account> getAll(Connection coon) {
String sql="select id,username,balance from account";
List<Account> query = getQuery(coon, Account.class, sql);
return query;
}
@Override
public Long getCount(Connection coon) {
String sql="select count(*) from account";
return getValue(coon, sql);
}
}
6.测试类
import com.jdbc.lhk.Bean.Account;
import com.jdbc.lhk.DAO.AccountDaoImpl;
import com.jdbc.lhk.utils.JdbcUtils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.util.List;
class AccountDaoImplTest {
AccountDaoImpl accountDaoImpl=new AccountDaoImpl();
@Test
void insert(){
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
Account account = new Account(3,"lhk",15000);
accountDaoImpl.insert(connection,account);
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void deleteById() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
accountDaoImpl.deleteById(connection,3);
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void updateById() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
Account account = new Account(1,"无忌",15000);
accountDaoImpl.updateById(connection,account);
System.out.println("修改成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void getAccountById() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
Account account = accountDaoImpl.getAccountById(connection, 1);
System.out.println(account);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void getAll() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
List<Account> all = accountDaoImpl.getAll(connection);
all.forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void getCount() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
Long count = accountDaoImpl.getCount(connection);
System.out.println("account表中共有"+count+"条记录");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
}
八、数据库连接池
1.C3P0数据库连接池技术
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<named-config name="MyC3P0">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="user">root</property>
<property name="password">000422</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">100</property>
<property name="maxStatements">50</property>
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import org.junit.Test;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
public class C3P0 {
@Test
public void testGetConnection() throws PropertyVetoException, SQLException {
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "com.mysql.jdbc.Driver" );
cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/test" );
cpds.setUser("root");
cpds.setPassword("000422");
cpds.setInitialPoolSize(10);
Connection coon = cpds.getConnection();
System.out.println(coon);
DataSources.destroy( cpds );
}
@Test
public void testGetConnection1() throws SQLException {
ComboPooledDataSource cpds = new ComboPooledDataSource("MyC3P0");
Connection conn = cpds.getConnection();
System.out.println(conn);
DataSources.destroy( cpds );
}
}
- DBCP数据库连接池技术
#基本配置信息
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=000422
#设置其他管理数据库连接池的相关属性
initialSize=10
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class DBCP {
@Test
public void testGetConnection() throws SQLException {
BasicDataSource source=new BasicDataSource();
source.setDriverClassName("com.mysql.jdbc.Driver");
source.setUrl("jdbc:mysql:///test");
source.setUsername("root");
source.setPassword("000422");
source.setInitialSize(10);
source.setMaxActive(10);
Connection coon = source.getConnection();
System.out.println(coon);
}
private static Properties properties=null;
static{
try {
properties = new Properties();
FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testGetConnection1() throws Exception {
DataSource source = BasicDataSourceFactory.createDataSource(properties);
Connection coon = source.getConnection();
System.out.println(coon);
}
}
- Druid数据库连接池技术
#基本配置信息
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=000422
#设置其他管理数据库连接池的相关属性
initialSize=10
maxActive=10
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class Druid {
@Test
public void getConnection() throws Exception {
Properties properties=new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
DataSource source = DruidDataSourceFactory.createDataSource(properties);
Connection conn = source.getConnection();
System.out.println(conn);
}
}
4.测试类
import com.jdbc.lhk.Bean.Account;
import com.jdbc.lhk.DAO.AccountDaoImpl;
import com.jdbc.lhk2.utils.JdbcUtils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.util.List;
class AccountDaoImplTest {
AccountDaoImpl accountDaoImpl=new AccountDaoImpl();
@Test
void insert(){
Connection connection = null;
try {
connection = JdbcUtils.getConnection1();
Account account = new Account(3,"lhk",15000);
accountDaoImpl.insert(connection,account);
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void deleteById() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection1();
accountDaoImpl.deleteById(connection,3);
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void updateById() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection1();
Account account = new Account(1,"无忌",15000);
accountDaoImpl.updateById(connection,account);
System.out.println("修改成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void getAccountById() {
Connection connection = null;
try {
connection = com.jdbc.lhk2.utils.JdbcUtils.getConnection3();
Account account = accountDaoImpl.getAccountById(connection, 1);
System.out.println(account);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void getAll() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection2();
List<Account> all = accountDaoImpl.getAll(connection);
all.forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
@Test
void getCount() {
Connection connection = null;
try {
connection = JdbcUtils.getConnection1();
Long count = accountDaoImpl.getCount(connection);
System.out.println("account表中共有"+count+"条记录");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(connection,null);
}
}
}
5.工具类
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static ComboPooledDataSource cpds = new ComboPooledDataSource("MyC3P0");
public static Connection getConnection1() throws SQLException {
Connection conn = cpds.getConnection();
return conn;
}
private static Properties properties=null;
private static DataSource source=null;
static {
try {
properties = new Properties();
FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));
properties.load(is);
source = BasicDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection2() throws Exception {
Connection coon = source.getConnection();
return coon;
}
private static DataSource source1;
static {
try {
Properties properties=new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
source1 = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection3() throws SQLException {
Connection conn = source1.getConnection();
return conn;
}
public static void closeResource(Connection connection, Statement ps){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void closeResource(Connection connection, Statement ps, ResultSet rs){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (rs!=null)
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
九、Apache-DBUtils实现CRUD操作
1.工具类
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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 JdbcUtils {
private static ComboPooledDataSource cpds = new ComboPooledDataSource("MyC3P0");
public static Connection getConnection1() throws SQLException {
Connection conn = cpds.getConnection();
return conn;
}
private static Properties properties=null;
private static DataSource source=null;
static {
try {
properties = new Properties();
FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));
properties.load(is);
source = BasicDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection2() throws Exception {
Connection coon = source.getConnection();
return coon;
}
private static DataSource source1;
static {
try {
Properties properties=new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
source1 = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection3() throws SQLException {
Connection conn = source1.getConnection();
return conn;
}
public static void closeResource(Connection connection, Statement ps){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void closeResource(Connection connection, Statement ps, ResultSet rs){
try {
if (ps!=null)
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (connection!=null)
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (rs!=null)
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void closeResource1(Connection connection, Statement ps, ResultSet rs){
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(connection);
}
}
2.测试类
import com.jdbc.lhk.Bean.Account;
import com.jdbc.lhk2.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.*;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class QueryRunnerTest {
@Test
public void testInsert() {
Connection conn = null;
try {
QueryRunner queryRunner = new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="insert into account(username,balance) values(?,?)";
int insertCount = queryRunner.update(conn, sql, "lhk", 12000);
System.out.println("成功添加了"+insertCount+"条数据");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
@Test
public void query1() {
Connection conn=null;
try {
QueryRunner queryRunner=new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="select id,username,balance from account where id=?";
BeanHandler<Account> handler = new BeanHandler<>(Account.class);
Account account = queryRunner.query(conn, sql, handler, 4);
System.out.println(account);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
@Test
public void query2() {
Connection conn = null;
try {
QueryRunner queryRunner=new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="select id,username,balance from account where id<?";
BeanListHandler<Account> handler = new BeanListHandler<>(Account.class);
List<Account> accounts = queryRunner.query(conn, sql, handler, 3);
accounts.forEach(System.out::println);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
@Test
public void query3() {
Connection conn = null;
try {
QueryRunner queryRunner=new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="select id,username,balance from account where id=?";
MapHandler handler = new MapHandler();
Map<String, Object> map = queryRunner.query(conn, sql, handler, 4);
System.out.println(map);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
@Test
public void query4() {
Connection conn = null;
try {
QueryRunner queryRunner=new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="select id,username,balance from account where id<?";
MapListHandler handler = new MapListHandler();
List<Map<String, Object>> list = queryRunner.query(conn, sql, handler, 3);
list.forEach(System.out::println);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
@Test
public void query5() {
Connection conn = null;
try {
QueryRunner queryRunner=new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="select count(*) from account";
ScalarHandler handler = new ScalarHandler();
var count = queryRunner.query(conn, sql, handler);
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
@Test
public void query6() {
Connection conn = null;
try {
QueryRunner queryRunner=new QueryRunner();
conn = JdbcUtils.getConnection3();
String sql="select id,username,balance from account where id=?";
ResultSetHandler<Account> handler = new ResultSetHandler<>() {
@Override
public Account handle(ResultSet resultSet) throws SQLException {
if (resultSet.next()){
int id=resultSet.getInt("id");
String username=resultSet.getString("username");
Double balance=resultSet.getDouble("balance");
Account account = new Account(id, username, balance);
return account;
}
return null;
}
};
Account account = queryRunner.query(conn, sql, handler, 4);
System.out.println(account);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.closeResource(conn,null);
}
}
}
|