Java连接数据库的几种方式

方式1:Driver获取连接

Driver driver = new com.mysql.cj.jdbc.Driver();
//	Driver driver = new com.mysql.jdbc.Driver();
		 
	String url = "jdbc:mysql://localhost:3306/test";
	//将用户名和密码封装在Properties中
	Properties info = new Properties();
	info.setProperty("user","root");
	info.setProperty("password","123456");
	Connection conn = driver.connect(url,info);
		
	System.out.println(conn);

方式2:使用反射获取连接驱动

//1.获取Driver实现类对象:通过反射
		Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
		Driver driver = (Driver) clazz.newInstance();
		//2.提供需要连接的数据库
		String url = "jdbc:mysql://localhost:3306/test";
		
		//3.提供连接需要的用户名和密码
		Properties info = new Properties();
		info.setProperty("user","root");
		info.setProperty("password","123456");
		//4.获取连接
		Connection conn = driver.connect(url,info);
		System.out.println(conn);

方式3:使用DriverManager

//1.获取 Driver实现类的对象
		Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
		Driver driver = (Driver) clazz.newInstance();
		
		//2、提供另外三个连接的基本信息
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "123456";
		//注册驱动
		DriverManager.registerDriver(driver);
		
		//获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);

方式4:使用DriverManager

//1、提供另外三个连接的基本信息
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "123456";
		//2.获取 Driver实现类的对象(可省略)
		Class.forName("com.mysql.cj.jdbc.Driver");
		
		//获取连接
		Connection conn = DriverManager.getConnection(url, user, password);
		System.out.println(conn);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值