下面是在JAVA中與MySQL建立連接的一個模塊:
[java]
- package com.han;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
-
- /**
- * SQL connection module
- * @author HAN
- *
- */
- public class Conn {
- Connection con;//Declare a Connection object
- String driver="com.mysql.jdbc.Driver";// the MySQL driver
- String url="jdbc:mysql://localhost:3306/db_jdbc";// URL points to destination database to manipulate
- String user="root";//user name for the specified database
- String pwd="hangaowen1212";//the corresponding password
- public Connection getConnection(){
- try {
- Class.forName(driver);// add MySQL driver
- System.out.println("Database driver is successfully added");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- con=DriverManager.getConnection(url,user,pwd);//create a connection object
- System.out.println("Database connection is successful");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return con;
- }
- public static void main(String[] args){
- Conn c=new Conn();
- c.getConnection();
- }
- }
附:MySQL相關配置
1. 下載MySQL,安裝(大小300多M)
2. 配置數據庫(打開MySQL建立用戶名,密碼,數據庫URL,端口號等);還要打開MySQL安裝目錄,找到mysql-connector-java-5.1.15-bin.jar這樣的文件加進CLASSPATH(CMD在電腦的系統環境變量中,eclipse在run configuration中)。