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

JDBC连接访问MySQL数据库
package com.lian.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectMySQL {
	
	/*
	 * 数据库的连接工具类
	 */
	private static final String Driver = "com.mysql.jdbc.Driver";
	private static final String DBURL = "jdbc:mysql://localhost:3306/db_user";
	private static final String UserName = "root";
	private static final String passWord = "root";
	
	private static Connection conn = null;
	
	/*
	 * 加载及注册JDBC驱动程序
	 */
	public ConnectMySQL() {
		try {
			Class.forName(Driver);
			System.out.println("Success load Mysql Driver!");	
		} catch (ClassNotFoundException e) {
			System.out.println("Error load Mysql Driver!");
			e.printStackTrace();
		} 
	}
	
	/*
	 * 建立数据库的连接
	 * @return
	 */
	public static Connection getConnection() {
		try {
			conn = DriverManager.getConnection(DBURL, UserName, passWord);
			System.out.println("Success connect Mysql Server!");
		} catch (SQLException e) {
			System.out.println("No connect Mysql Server!");
			e.printStackTrace();
		}
		return conn;	
	}	

}
?
package com.lian.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC {

	private static Connection conn = null;
	private static Statement stmt = null;
	private static ResultSet rs = null;
	
	/*
	 *测试JDBC连接MySQL
	 * @return args
	 */
	public static void main(String[] args) {

		ConnectMySQL connectMySQL = new ConnectMySQL();
		conn = ConnectMySQL.getConnection();
		try {
			stmt = conn.createStatement();//创建Statement对象,准备执行SQL语句
			rs = stmt.executeQuery("select * from user");//执行SQL语句
			//结果处理
			while (rs.next()) {
				String userName = rs.getString("userName");
				String phone = rs.getString("phone");
				System.out.println("userName:" + userName + "  " + "phone:" + phone);
			}
		} catch (SQLException e) {
			System.out.print("No data!");
			e.printStackTrace();
		} finally {
			// 释放资源
			try {
				if (rs == null) rs.close();
				if (stmt == null) stmt.close();
				if (conn == null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}