java JDBC简单封装(MySQL)
此次封装使用maven构建
- 目录结构
- product数据库表建表语句
create table `product` (
`p_id` int(32) not null unique primary key auto_increment,
`p_name` varchar(50) not null,
`p_size` double not null,
`p_price` double not null,
`p_date` datetime not null default now()
) engine=innodb;
- db.properties文件(位于src/main/resources文件夹下)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/gdlt?characterEncoding=utf8&useSSL=true
username=root
password=1862
jdbcConnectionInitSize=10
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.unicom</groupId>
<artifactId>testJDBC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
package com.unicom;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.Properties;
import java.util.logging.Logger;
import javax.sql.DataSource;
public class ConnectionPools implements DataSource {
private ConnectionPools() {
}
private static class SingletonHolder {
private final static ConnectionPools instance = new ConnectionPools();
}
public static ConnectionPools getInstance() {
return SingletonHolder.instance;
}
private static LinkedList<Connection> linkedlist = new LinkedList<Connection>();
private static String driver;
private static String url;
private static String username;
private static String password;
private static int jdbcConnectionInitSize;
private static int max = 1;
static {
InputStream is = ConnectionPools.class
.getResourceAsStream("/db.properties");
Properties prop = new Properties();
try {
prop.load(is);
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
jdbcConnectionInitSize = Integer
.parseInt(prop.getProperty("jdbcConnectionInitSize"));
Class.forName(driver);
for (int i = 0; i < jdbcConnectionInitSize; i++) {
Connection conn = DriverManager.getConnection(url, username,
password);
linkedlist.add(conn);
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public Connection getConnection() throws SQLException {
if (linkedlist.size() == 0 && max <= 5) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < jdbcConnectionInitSize; i++) {
Connection conn = DriverManager.getConnection(url, username,
password);
linkedlist.add(conn);
}
max++;
}
if (linkedlist.size() > 0) {
final Connection conn1 = linkedlist.removeFirst();
return (Connection) Proxy.newProxyInstance(
conn1.getClass().getClassLoader(),
conn1.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
if (!method.getName().equalsIgnoreCase("close")) {
return method.invoke(conn1, args);
} else {
linkedlist.add(conn1);
return null;
}
}
});
}
return null;
}
@Override
public Connection getConnection(String username, String password)
throws SQLException {
return null;
}
public void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if (st != null) {
try {
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.unicom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DBUtil {
private ConnectionPools connectionPools = ConnectionPools.getInstance();
public DBUtil() {
}
public boolean execute(List<String> sqls) {
Connection conn = null;
Statement st = null;
boolean res = true;
try {
conn = connectionPools.getConnection();
conn.setAutoCommit(false);
st = conn.createStatement();
for (String sql : sqls) {
st.execute(sql);
}
conn.commit();
return res;
} catch (Exception e) {
e.printStackTrace();
res = false;
return res;
} finally {
connectionPools.release(conn, st, null);
}
}
public List<Map<String, Object>> query(String sql, Object... params) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Map<String, Object>> list = new ArrayList<>();
try {
conn = connectionPools.getConnection();
ps = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rs = ps.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
while (rs.next()) {
Map<String, Object> rowData = new HashMap<String, Object>();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
connectionPools.release(conn, ps, rs);
}
}
}
package test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.unicom.DBUtil;
public class ProductTest {
public static void main(String[] args) {
ProductTest productTest = new ProductTest();
productTest.testQuery();
}
public void testQuery() {
String querySql = "select p_id,p_name,p_price,p_size,p_date from product";
DBUtil dbUtil = new DBUtil();
List<Map<String, Object>> list = dbUtil.query(querySql, null);
Iterator<Map<String, Object>> iterator = list.iterator();
while (iterator.hasNext()) {
Map<String, Object> map = iterator.next();
System.out.println("id:" + map.get("p_id"));
System.out.println("name:" + map.get("p_name"));
System.out.println("price:" + map.get("p_price"));
System.out.println("size:" + map.get("p_size"));
System.out.println("date:" + map.get("p_date"));
System.out.println("-----------------");
}
}
public void insertTest() {
DBUtil dbUtil = new DBUtil();
String insertSql = "insert into product(p_name,p_price,p_size,p_date) values('"
+ "手机" + "','" + 2324 + "','" + 12 + "','"
+ "2018-12-25 11:55:00" + "')";
List<String> sqls = new ArrayList<>();
sqls.add(insertSql);
sqls.add(insertSql);
boolean res = dbUtil.execute(sqls);
System.out.println("插入数据" + res);
}
}
id:1
name:电脑
price:2333.0
size:12.0
date:2018-12-25 11:32:03.0
------------
id:2
name:手机
price:2344.0
size:12.0
date:2018-12-25 11:55:00.0