Establish Java and database connection configuration file properties in eclipse

报错:Exception in thread “main” java.lang.NullPointer Exception: inStream parameter is null

The first step: the
cause of the problem:
refer to this link
https://www.cnblogs.com/xc1370338904/p/11212687.html

Match the source code here:

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql?serverTimezone=UTC
jdbc.userName=root
jdbc.passWord=636895
package jdbc;

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


public class JdbcUtils {
    
    
	private static Properties properties=null;
	static {
    
    
			//初始化properties,即加载dbconfig.properties配置文件1次到properties中
			try {
    
    
				//1.加载配置文件
				InputStream inputStream=JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
				properties =new Properties();
				properties.load(inputStream);
			} catch (IOException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
    
    
		Connection connection=JdbcUtils.getConnection();
		
		System.out.println(connection);
	}
	
	public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
    
    
		//2.加载驱动类
		Class.forName(properties.getProperty("jdbc.driverClassName"));
		//3.通过Drivermanager得到connection
		Connection connection=DriverManager.getConnection(properties.getProperty("jdbc.url"), properties.getProperty("jdbc.userName"), properties.getProperty("jdbc.passWord"));
		return connection;
		}
	
}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44421869/article/details/103209351