本人这段时间在公司学习neo4j的相关知识,带我的高级开发让我尝试着不用框架,用数据库连接池,实现对neo4j数据库的增删改查。在网上经过一番搜索以后,发现很多帖子代码给的都不全,需要自己修改。故现在放出我结合网上帖子和自己的修改以后的代码,粘贴复制即可用。
1、JdbcConnectionPoolFactory.java
package demo;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ${TODO} 写点注释吧
* @author: duan_lian
* @date: 2020/1/3 9:55
* @version: V1.0
* @review: duan_lian/2020/1/3 9:55
*/
public class JdbcConnectionPoolFactory {
/**
* @Field: pool
* 数据库连接池
*/
/**
* @Method: getConnection
* @Description: 从数据库连接池中获取数据库连接对象
* @return Connection数据库连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
JdbcConnectionsPool pool = new JdbcConnectionsPool();
return pool.getConnection();
}
/**
* @Method: release
* @Description: 释放资源,
* 释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
//关闭存储查询结果的ResultSet对象
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if (st != null) {
try {
//关闭负责执行SQL命令的Statement对象
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
//关闭Connection数据库连接对象
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static List<Object> executeSql(String sql, Class c) throws SQLException, IllegalAccessException, InstantiationException {
List<Object> objects = new ArrayList<>();
Field[] fields = c.getDeclaredFields();
Connection conn = JdbcConnectionPoolFactory.getConnection();
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
Object o=c.newInstance();
for (Field f : fields) {
f.setAccessible(true);
if (f.getType() == java.util.List.class) {
// 如果是List类型,得到其Generic的类型
Type genericType = f.getGenericType();
// 如果是泛型参数的类型
if (genericType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericType;
//得到泛型里的class类型对象
Class<?> genericClazz = (Class<?>) pt.getActualTypeArguments()[0];
}
}
System.out.println(resultSet.getString("n"));
}
//关闭所有的数据库资源
JdbcConnectionPoolFactory.release(conn, statement, resultSet);
}
return null;
}
public static List<Map<String, String>> executeSql(String sql, String...returnKeys) throws SQLException {
List<Map<String,String>> maps = new ArrayList<>();
Connection conn = JdbcConnectionPoolFactory.getConnection();
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
Map<String, String> map = new HashMap();
for (String key:returnKeys) {
map.put(key, resultSet.getString(key));
}
maps.add(map);
}
//关闭所有的数据库资源
JdbcConnectionPoolFactory.release(conn, statement, resultSet);
return maps;
}
}
2、JdbcConnectionsPool.java
package demo;
import javax.sql.DataSource;
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.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;
/**
* ${TODO} 写点注释吧
* @author: duan_lian
* @date: 2020/1/3 9:56
* @version: V1.0
* @review: duan_lian/2020/1/3 9:56
*/
public class JdbcConnectionsPool implements DataSource {
/*
* 使用静态块代码,初始化连接池,创建连接池的中最小链接数量连接,
* 创建linkedlist集合,将这些连接放入集合中
*/
/**创建linkedlist集合 **/
private static LinkedList<Connection> linkedlist1 = new LinkedList<Connection>();
private static String driver = "org.neo4j.jdbc.Driver";
private static String url = "jdbc:neo4j:bolt://localhost/";
private static String username = "neo4j";
private static String password = "123456";
/**最小连接数量**/
private static int jdbcConnectionInitSize = 2;
/** 当前最大连接数量=max*jdbcConnectionInitSize**/
private static int max = 5;
static {
try {
jdbcConnectionInitSize = Integer.parseInt("5");
Class.forName(driver);
/** 创建最小连接数个数据库连接对象以备使用**/
for (int i = 0; i < jdbcConnectionInitSize;i++ ) {
Connection conn= (Connection) DriverManager.getConnection(url, username, password);
System.out.println("获取到了链接" + conn);
//将创建好的数据库连接对象添加到Linkedlist集合中
linkedlist1.add(conn);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
/**
* 实现数据库连接的获取和新创建
**/
@Override
public Connection getConnection() throws SQLException {
//如果集合中没有数据库连接对象了,且创建的数据库连接对象没有达到最大连接数量,可以再创建一组数据库连接对象以备使用
if (linkedlist1.size() == 0 && max <= 5) {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jdbcConnectionInitSize; i++) {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("获取到了链接" + conn);
//将创建好的数据库连接对象添加到Linkedlist集合中
linkedlist1.add(conn);
}
max++;
}
if (linkedlist1.size()>0) {
//从linkedlist集合中取出一个数据库链接对象Connection使用
final Connection conn1= linkedlist1.removeFirst();
System.out.println("linkedlist1数据库连接池大小是" + linkedlist1.size());
/*返回一个Connection对象,并且设置Connection对象方法调用的限制,
*当调用connection类对象的close()方法时会将Connection对象重新收集放入linkedlist集合中。
*/
Class<?>[] interfaces=new Class[]{Connection.class};
return (Connection) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
//这里换成JdbcConnectionsPool.class.getClassLoader();也行
interfaces, 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 {
linkedlist1.add(conn1);
System.out.println(conn1 + "对象被释放,重新放回linkedlist集合中!");
System.out.println("此时Linkedlist集合中有" + linkedlist1.size() + "个数据库连接对象!");
return null;
}
}
});
}else {
System.out.println("连接数据库失败!");
}
return null;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
}
3、TestJdbcPool.java
package demo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* ${TODO} 写点注释吧
* @author: duan_lian
* @date: 2020/1/3 9:58
* @version: V1.0
* @review: duan_lian/2020/1/3 9:58
*/
public class TestJdbcPool {
/** 查询**/
public static void query() throws SQLException {
Connection conn= JdbcConnectionPoolFactory.getConnection();
String sql = " MATCH (n:Artist) RETURN n.name ";
Statement statement = conn.createStatement();
ResultSet resultSet= statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("n.name"));
}
}
/** 增加**/
public static void add() throws SQLException {
Connection conn = JdbcConnectionPoolFactory.getConnection();
String sql = "CREATE (n:Artist{name:'duanlian'}) RETURN n.name ";
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("n.name"));
}
}
/** 更新**/
public static void update() throws SQLException {
Connection conn = JdbcConnectionPoolFactory.getConnection();
String sql = "MATCH (n:Artist{name:'duanlian'}) WHERE n.name = 'duanlian' SET n.name ='duanlianTest' ";
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("n.name"));
}
statement.close();
//关闭所有的数据库资源
JdbcConnectionPoolFactory.release(conn, statement, resultSet);
}
/** 删除 **/
public static void delete() throws SQLException {
Connection conn = JdbcConnectionPoolFactory.getConnection();
String sql = "MATCH (n:Artist{name:'duanlianTest'}) delete n ";
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("n.name"));
}
}
public static void main(String[] args) throws SQLException {
/** 实例化封装了有关数据库类方法类的对象**/
JdbcConnectionPoolFactory jcpt = new JdbcConnectionPoolFactory();
System.out.println("*************************************查询*******************************************");
query();
System.out.println("*************************************添加*******************************************");
add();
System.out.println("*************************************查询*******************************************");
query();
System.out.println("*************************************更新*******************************************");
update();
System.out.println("*************************************查询*******************************************");
query();
System.out.println("*************************************删除*******************************************");
delete();
System.out.println("*************************************查询*******************************************");
query();
}
}
运行结果如下图所示:

京公网安备 11010502036488号