1. 程式人生 > >多線程之模擬數據庫連接

多線程之模擬數據庫連接

out set rest play ann sta obj imp next

學習持久化之前,肯定會去連接數據庫來進行數據的各種操作,如增、刪、改、查,所以對此咋們直接寫了一個工具類BaseDAO,今天學習了多線程,所以決定寫一個多線程模擬工具類連接數據庫。好吧,其實老師要求的。

技術分享
 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 }
多線程模擬連接數據庫工具類

如果大家還有其他的方式,用多線程的方式來實現模擬連接數據庫的工具類,歡迎共享一下,謝謝。

多線程之模擬數據庫連接