JDBC连接数据库【Java】

写在前面的话:

  1. 参考资料:尚硅谷视频
  2. 本章内容:使用JDBC连接MySQL数据库
  3. IDE:eclipse
  4. JDK:Java8

目录

1.准备连接数据库的4个字符串

2.通过InputStream流获取jdbc.properties文件中的信息

3.准备读取文件中的信息,加载文件中的信息

4.从文件中获取信息,并赋值

5.获取数据库驱动程序

6.进行连接

7.查看是否连接成功!

8.完整代码可运行


连接数据库,共分为7个步骤。 

  1. 准备连接数据库的4个字符串
  2. 通过InputStream流获取jdbc.properties文件中的信息
  3. 准备读取文件中的信息,加载文件中的信息
  4. 从文件中获取信息,并赋值
  5. 获取数据库驱动程序
  6. 进行连接(获取连接)
  7. 查看是否连接成功!

1.准备连接数据库的4个字符串

String driver = null;//下载的MySQL驱动
String jdbcUrl = null;//下载的MySQL驱动包地址
String jdbcUser = null;//数据库的用户名
String jdbcPassword = null;//数据库的密码

2.通过InputStream流获取jdbc.properties文件中的信息

InputStream inputStream =  getClass().getClassLoader().getResourceAsStream("exer01//jdbc.properties");

3.准备读取文件中的信息,加载文件中的信息

Properties properties = new Properties();
properties.load(inputStream);

4.从文件中获取信息,并赋值

文件内容:(本文章更新内容)

driver=com.mysql.cj.jdbc.Driver
jdbcURL=jdbc:mysql://localhost:3306/数据库名称
user=数据库的用户名
password=数据库的密码
driver = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcURL");
jdbcUser = properties.getProperty("user");
jdbcPassword = properties.getProperty("password");

5.获取数据库驱动程序

这里需要用到反射的知识,不了解可以点击链接,查看星与梦想star_dream的文章

Class.forName(driver);

6.进行连接

Connection connection =  DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPassword);

7.查看是否连接成功!

System.out.println("数据库连接成功:"+connection);

8.完整代码可运行

package exer01;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class TestDriverMannage {

	public static void main(String[] args) throws Exception {
		
		TestDriverMannage t = new TestDriverMannage();
		
		t.openConnection();
		
	}
	
	public  void openConnection() throws Exception {
		
		//1.准备连接数据库的4个字符串
		String driver = null;
		String jdbcUrl = null;
		String jdbcUser = null;
		String jdbcPassword = null;
		
		//2.通过InputStream流获取jdbc.properties文件中的信息		
		InputStream inputStream =  getClass().getClassLoader().getResourceAsStream("exer01//jdbc.properties");
		
		//3.准备读取文件中的信息
		Properties properties = new Properties();

		//加载文件中的信息
		properties.load(inputStream);
		
		//4.从文件中获取信息,并赋值
		driver = properties.getProperty("driver");
		jdbcUrl = properties.getProperty("jdbcURL");
		jdbcUser = properties.getProperty("user");
		jdbcPassword = properties.getProperty("password");
		
		//5.获取数据库驱动程序
		Class.forName(driver);
		
		//6.进行连接
		Connection connection =  DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPassword);
		
		//7.查看是否连接成功
		System.out.println("数据库连接成功:"+connection);
	}
}

效果展示:

posted @ 2022-04-24 20:17  辰梦starDream  阅读(1)  评论(0编辑  收藏  举报  来源