日期:2014-05-16  浏览次数:20728 次

java连接mysql

?

public class UserDAO {
	private final static String dataBaseName = "user";  //数据库名称
	private final static String tableName = "user";
	private Connection connection = null;
	private String userName = "root";   //用户名
	private String password = "";   //密码
	UserDAO(){
		getConnect(); 
	}
	public void  getConnect(){
		if(connection != null) return; 
		String driverName = "com.mysql.jdbc.Driver"; 
		String url = "jdbc:mysql://127.0.0.1:3306/" + dataBaseName;
		try {
			Class.forName(driverName); 
			connection = DriverManager.getConnection(url, userName, password); 
			String sql = "create table if not exists " + tableName + 
			" (uid varchar(64), platformAddress varchar(64), primary key (uid)) ";
			PreparedStatement ps;
			ps = connection.prepareStatement(sql); 
			ps.executeUpdate();  
		} catch (Exception e) {
			
		}
	}
}

?需要注意的问题:

1、(win 7 系统)在开始-->搜索 , 然后输入“服务”,打开服务列表,检查一下mysql是否为开启状态。

2、jdbc的驱动包要加到“Referenced Libraries”里,下载地址是“http://www.mysql.com/downloads/” 里面的Connector/J

?