Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.*;
  3. import java.net.*;
  4.  
  5. public class URLClassLoaderTest
  6. {
  7. private static Connection conn;
  8. //定义一个获取数据库连接方法
  9. public static Connection getConn(String url ,
  10. String user , String pass) throws Exception
  11. {
  12. if (conn == null)
  13. {
  14. // 创建一个URL数组
  15. URL[] urls = {new URL("file:mysql-connector-java-3.1.10-bin.jar")};
  16. // 以默认的ClassLoader作为父ClassLoader,创建URLClassLoader
  17. URLClassLoader myClassLoader = new URLClassLoader(urls);
  18. // 加载MySQL的JDBC驱动,并创建默认实例
  19. Driver driver = (Driver)myClassLoader.loadClass("com.mysql.jdbc.Driver").newInstance();
  20. // 创建一个设置JDBC连接属性的Properties对象
  21. Properties props = new Properties();
  22. // 至少需要为该对象传入user和password两个属性
  23. props.setProperty("user" , user);
  24. props.setProperty("password" , pass);
  25. // 调用Driver对象的connect方法来取得数据库连接
  26. conn = driver.connect(url , props);
  27. }
  28. return conn;
  29. }
  30. public static void main(String[] args)throws Exception
  31. {
  32. System.out.println(getConn("jdbc:mysql://localhost:3306/mysql"
  33. , "root" , "32147"));
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement