JAVA中MySQL建立连接

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

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中)。

3. 若使用Java DB则有2种模式:嵌入模式(embeded mode)和客户服务器模式(client/server)。embeded mode中Derby和JVM绑定,省去了很多数据库连接的配置,但是相应的2个应用JVM的程序就不能同时使用一个数据库,否则会报错Exception。详见后面的文章:Java DB Derby的使用。

posted on 2012-01-29 23:12  java课程设计例子  阅读(416)  评论(0编辑  收藏  举报