集合多线程网络编程JDBC连接池反射综合应用
Posted luojack
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了集合多线程网络编程JDBC连接池反射综合应用相关的知识,希望对你有一定的参考价值。
1、使用TCP连接服务器和客户端。
2、结合反射的知识、创建JDBC和连接池。
3、客户端输入信息并保存到一个对象中,发送到服务器。
4、服务器接收对象,通过JDBC存储进数据库中。
5、把服务器放到线程中,保持启动状态。
6、客户端读取数据库的数据信息,放到集合中。
7、遍历集合,输出数据库的数据。
服务器和客户端的项目结构:
服务器
客户端
实体类:
package com.luo.project.pojo; import java.io.Serializable; public class User implements Serializable{ /** * */ private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } public User(Integer id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } public User() { super(); // TODO Auto-generated constructor stub } }
Dao层:
package com.luo.project.dao; import java.util.List; import com.luo.project.pojo.User; public interface UserDao { // 插入用户 public int insertUser(User user); // 查询所有用户 public List<User> queryAllUser(); }
Dao实现层:
package com.luo.project.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.alibaba.druid.stat.JdbcConnectionStat; import com.luo.project.dao.UserDao; import com.luo.project.pojo.User; import com.luo.project.util.JDBCUtil; public class UserDaoImpl implements UserDao { @Override public int insertUser(User user) { return JDBCUtil.insertUser(user); } @Override public List<User> queryAllUser() { return JDBCUtil.queryAllUser(User.class); } }
JDBC工具类:
package com.luo.project.util; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.luo.project.pojo.User; public class JDBCUtil { // 创建读取文件的properties类 private static Properties properties = new Properties(); private static DataSource dataSource=null; static { try { System.out.println("正在创建类加载器..."); // 获取类加载器 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // 通过加载器获取项目下的配置文件的字节流 InputStream inputStream = contextClassLoader.getResourceAsStream("db.properties"); System.out.println("正在加载配置文件..."); // 加载配置文件 properties.load(inputStream); System.out.println("配置文件加载完毕..."); dataSource=DruidDataSourceFactory.createDataSource(properties); Class.forName(properties.getProperty("driverClassName")); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException("连接失败!", e); } } public static void close(Connection connection, PreparedStatement ps, ResultSet rs) { if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } } public static int insertUser(Object obj) { // String sql="insert into User(name,age) values(?,?)"; StringBuilder sb=new StringBuilder(); sb.append("insert into "); sb.append(obj.getClass().getSimpleName()); sb.append("("); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); sb.append(fieldName+","); } sb.deleteCharAt(sb.length()-1); sb.append(")"); sb.append("values ("); for (Field field : fields) { sb.append("?,"); } sb.deleteCharAt(sb.length()-1); sb.append(")"); Connection connection=null; PreparedStatement ps=null; try { connection=JDBCUtil.getConnection(); connection.setAutoCommit(false); ps= connection.prepareStatement(sb.toString()); for(int i=0;i<fields.length;i++){ // 字段数组 Field field = fields[i]; field.setAccessible(true); Object fieldValue = field.get(obj); ps.setObject(i+1, fieldValue); } int row = ps.executeUpdate(); connection.commit(); return row; } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCUtil.close(connection, ps, null); } return 0; } public static <T> List<T> queryAllUser(Class<T> clz) { // String sql="select * from user"; String sql="select * from "+ clz.getSimpleName(); Connection connection=null; PreparedStatement ps=null; ResultSet rs=null; List<T> list=new ArrayList<T>(); try { connection=JDBCUtil.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()){ T object = clz.newInstance(); Field[] Fields = clz.getDeclaredFields(); for (Field field : Fields) { String fieldName = field.getName(); Object value = rs.getObject(fieldName); field.setAccessible(true); field.set(object, value); } list.add(object); } connection.commit(); return list; } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }finally{ JDBCUtil.close(connection, ps, rs); } return null; } }
服务器的主类和线程类:
主类:
package com.luo.project.test; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import com.luo.project.dao.impl.UserDao; import com.luo.project.dao.impl.UserDaoImpl; import com.luo.project.pojo.User; import com.luo.project.thread.LoginThread; //服务器 public class Service { public static void main(String[] args) throws IOException { System.out.println("服务器启动..."); ServerSocket serverSocket=serverSocket = new ServerSocket(9000); // 每次客户端连接,都会实例一个socket对象 while(true){ Socket socket=serverSocket.accept(); LoginThread loginThread = new LoginThread(socket); loginThread.start(); } } }
线程:
package com.luo.project.thread; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import com.luo.project.dao.impl.UserDao; import com.luo.project.dao.impl.UserDaoImpl; import com.luo.project.pojo.User; public class LoginThread extends Thread { private Socket socket; public LoginThread(Socket socket) { super(); this.socket=socket; } @Override public void run() { InputStream inputStream=null; ObjectInputStream objectInputStream=null; try { System.out.println("客户端已连接!"); // 接受客户端的数据 inputStream = socket.getInputStream(); objectInputStream=new ObjectInputStream(inputStream); User user = (User) objectInputStream.readObject(); System.out.println(user); // 将数据存入数据库中 UserDao userDao=new UserDaoImpl(); int row = userDao.insertUser(user); System.out.println("数据被影响的行数:"+row); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客户端的主类:
package com.luo.project.test; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.luo.project.dao.UserDao; import com.luo.project.dao.impl.UserDaoImpl; import com.luo.project.pojo.User; //客户端 public class Client { public static void main(String[] args) { System.out.println("客户端启动..."); Socket socket=null; OutputStream outputStream=null; Scanner scanner=new Scanner(System.in); ObjectOutputStream objectOutputStream=null; List<User> list=new ArrayList<>(); try { socket=new Socket("127.0.0.1",9000); outputStream= socket.getOutputStream(); objectOutputStream=new ObjectOutputStream(outputStream); //向服务器发送数据 System.out.print("请输入用户名称:"); String name = scanner.nextLine(); System.out.print("请输入用户年龄:"); int age = scanner.nextInt(); User user=new User(null, name, age); objectOutputStream.writeObject(user); objectOutputStream.flush(); //遍历数据库 UserDao userDao=new UserDaoImpl(); List<User> users = userDao.queryAllUser(); System.out.println("遍历数据库:"); for (User u : users) { System.out.println(u); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { objectOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
db.properties配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/first_project username=root password=123456 maxActive=10
测试类:
package com.luo.project.test; import java.util.List; import org.junit.Test; import com.luo.project.dao.impl.UserDao; import com.luo.project.dao.impl.UserDaoImpl; import com.luo.project.pojo.User; public class UserTest { private UserDao userDao=new UserDaoImpl(); @Test public void insertTest(){ User user=new User(null, "乔布斯", 45); int insertUser = userDao.insertUser(user); System.out.println(insertUser); } @Test public void queryAllUser(){ List<User> queryAllUser = userDao.queryAllUser(); for (User user : queryAllUser) { System.out.println(user); } } }
数据库表:
以上是关于集合多线程网络编程JDBC连接池反射综合应用的主要内容,如果未能解决你的问题,请参考以下文章