Java中MySQL建立连接


下面是在JAVA中与MySQL建立连接的一个模块:

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

附:MySQL相关配置

1. 下载MySQL,安装(大小300多M)

2. 配置数据库(打开MySQL建立用户名,密码,数据库URL,端口号等);还要打开MySQL安装目录,找到mysql-connector-java-5.1.15-bin.jar这样的文件加进CLASSPATH(CMD在电脑的系统环境变量中,eclipse在run configuration中)。

相关内容