学习持久化之前,肯定会去连接数据库来进行数据的各种操作,今天学习了多线程,所以决定写一个多线程模拟工具类连接数据库。
1 import com.sun.org.apache.xpath.internal.SourceTree;
2 import jdk.internal.util.xml.impl.Input;
3
4 import java.sql.*;
5 import java.sql.Connection;
6 import java.util.ArrayList;
7 import java.util.List;
8 import java.util.Scanner;
9
10 /**
11 * Created by 123 on 2017/07/02.
12 */
13 public class GetConnection {
14
15 static Scanner input = new Scanner(System.in);
16 static String url = null;
17 static String pwd = null;
18 static String name = null;
19 static Conn con = new Conn();
20 static PreparedStatement ps = null;
21 static ResultSet rs = null;
22
23 public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
24
25
26 while (true) {
27 System.out.println("url:");
28 url = input.next();
29
30 System.out.println("name");
31 name = input.next();
32
33 System.out.println("pwd");
34 pwd = input.next();
35
36 Connection conn = getConnection();
37 System.out.println(conn);
38 Fount();
39 Thread.sleep(1000);
40 //先mian线程,再子线程
41 }
42 }
43
44 static Connection conn = null;
45
46 //获取连接
47 public static Connection getConnection() throws SQLException, ClassNotFoundException {
48 try {
49 if (conn == null || conn.isClosed()) {
50 Class.forName("com.mysql.jdbc.Driver");
51 conn = DriverManager.getConnection(url, name, pwd);
52 }
53 } catch (ClassNotFoundException e) {
54 e.printStackTrace();
55 } catch (SQLException e) {
56 e.printStackTrace();
57 } finally {
58 return conn;
59 }
60 }
61
62 public static ResultSet executeQuery(String sql, Object... obj) throws ClassNotFoundException, SQLException {
63 conn = getConnection();
64 ps = conn.prepareStatement(sql);
65 for (int i = 0; i < obj.length; i++) {
66 ps.setObject(i + 1, obj[i]);
67 }
68 return ps.executeQuery();
69 }
70
71 private static void Fount() throws InterruptedException {
72 Thread t = new Thread(new Runnable() { //匿名类
73 public void run() {
74 List list = new ArrayList();
75 try {
76 rs = executeQuery("select * from topic");
77 if (rs != null) {
78 while (rs.next()) {
79 String name = rs.getString("tname");
80 list.add(name);
81 }
82 }
83
84 for (Object item : list) {
85 System.out.println(item);
86 }
87 } catch (ClassNotFoundException e) {
88 e.printStackTrace();
89 } catch (SQLException e) {
90 e.printStackTrace();
91 }
92 }
93
94 });
95 t.start();
96 t.join(1000);
97
98 }
99 }
多线程模拟连接数据库工具类
其实我仔细看了看,发现其实在main方法中可以不用调用Thread.sleep(1000);静态方法的,有点多此一举,因为我在子线程中调用
t.join(1000);方法,进行了插队的行为,所以就不用睡眠方法了。
如果大家还有其他的方式,用多线程的方式来实现模拟连接数据库的工具类,欢迎共享一下,谢谢。