歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中MySQL建立連接

Java中MySQL建立連接

日期:2017/3/1 10:36:02   编辑:Linux編程

下面是在JAVA中與MySQL建立連接的一個模塊:

[java]
  1. package com.han;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. /**
  6. * SQL connection module
  7. * @author HAN
  8. *
  9. */
  10. public class Conn {
  11. Connection con;//Declare a Connection object
  12. String driver="com.mysql.jdbc.Driver";// the MySQL driver
  13. String url="jdbc:mysql://localhost:3306/db_jdbc";// URL points to destination database to manipulate
  14. String user="root";//user name for the specified database
  15. String pwd="hangaowen1212";//the corresponding password
  16. public Connection getConnection(){
  17. try {
  18. Class.forName(driver);// add MySQL driver
  19. System.out.println("Database driver is successfully added");
  20. } catch (ClassNotFoundException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. try {
  25. con=DriverManager.getConnection(url,user,pwd);//create a connection object
  26. System.out.println("Database connection is successful");
  27. } catch (SQLException e) {
  28. // TODO Auto-generated catch block
  29. e.printStackTrace();
  30. }
  31. return con;
  32. }
  33. public static void main(String[] args){
  34. Conn c=new Conn();
  35. c.getConnection();
  36. }
  37. }

附:MySQL相關配置

1. 下載MySQL,安裝(大小300多M)

2. 配置數據庫(打開MySQL建立用戶名,密碼,數據庫URL,端口號等);還要打開MySQL安裝目錄,找到mysql-connector-java-5.1.15-bin.jar這樣的文件加進CLASSPATH(CMD在電腦的系統環境變量中,eclipse在run configuration中)。

Copyright © Linux教程網 All Rights Reserved