java学习笔记——eclipse连接MySQL

**

java学习笔记——eclipse连接MySQL

**

1. 导入jdbc驱动包
鼠标右键工程名字–>Build Path–>Configure Build Path…
java学习笔记——eclipse连接MySQL
在Libraies中选Add External JARs找到本地的jbdc驱动包,然后Apply and Close即可
java学习笔记——eclipse连接MySQL
2. 加载jdbc驱动及验证

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

public class DbUtil {
	 //jdbc:协议 mysql:子协议 localhost:服务器 3306:端口号 student:数据库名字
	private static String dbUrl="jdbc:mysql://localhost:3306/student";
	private static String dbUser="root";
	private static String dbPassWord="123456";
	private static String jdbcName="com.mysql.jdbc.Driver";
	//链接数据库的方法
	public Connection getConnection() throws ClassNotFoundException, SQLException {
		Connection conn = null;
		//反射机制
		Class.forName(jdbcName);
		//获取conn对象
		conn=DriverManager.getConnection(dbUrl, dbUser, dbPassWord);
		return conn;
	}
	//关闭数据库的方法
	public void closeCon(Connection conn) throws SQLException {
		if (conn!=null) {
			conn.close();
		}
	}
	public static void main(String[] args) {
		DbUtil dbUtil=new DbUtil();
		Connection conn=null;
		try {
			conn=dbUtil.getConnection();
			if (conn!=null) {
				System.out.println("数据库连接成功!");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("缺少驱动包");
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("数据库连接失败");
			e.printStackTrace();
		}
	}
}

  • 运行结果:
    java学习笔记——eclipse连接MySQL