Java--IDEA中使用properties配置文件通过JDBCUtils进行MySQL数据连接(NullPointerException,NoClassDefFoundError..)

在学习通过使用properties配置文件通过JDBCUtils进行MySQL数据连接,经常会出现NullPointerException或者NoClassDefFoundError 等错误,令人非常头疼,今天我就归纳了一些问题出现的原因,以及一些解决方案。

Properties load 方式有两种方式

void load(InputStream inStream) 

void load(Reader reader)

 

工程目录结构:

 

JDBCUtils

package main;

import java.io.*;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

   static{

       try {
           Properties pro = new Properties();
           //方式1 Xxx.class.getClassLoader().getResource 注意此方法路径中不能包含中文
           String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
           System.out.println(path);
           pro.load(new FileReader(path));
           //方式2 Xxx.class.getClassLoader().getResourceAsStream
        /*   InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
           pro.load(in);*/
            //方式3 Xxx.class.getResource
          /* String path = JDBCUtils.class.getResource("jdbc.properties").getPath();
           pro.load(new FileReader(path));*/
           //方式4 Xxx.class.getResourceAsStream
         /*  InputStream in = JdbcSQL.class.getResourceAsStream("jdbc.properties");
           pro.load(in);*/
           //方式5 resources/jdbc.properties
//           pro.load(new FileInputStream("resources/jdbc.properties"));

           url = pro.getProperty("url");
           user = pro.getProperty("user");
           password = pro.getProperty("password");
           driver = pro.getProperty("driver");
           Class.forName(driver);

       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }

   public static Connection getConnection() throws SQLException {
       return DriverManager.getConnection(url, user, password);
   }

    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

/*   public  static void close(Statement stmt, Connection conn){
       close(null, stmt, conn);
   }*/

   }
}

 

 

JdbcSQL.java

package main;

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

public class JdbcSQL {
    public static void main(String[] args) {
        //此处为了测试jdbc.properties路径
        String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
        System.out.println(path);
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input user name:");
        String user = sc.nextLine();
        System.out.println("Please input password:");
        String password = sc.nextLine();

        boolean flag = new JdbcSQL().login(user, password);
        if (flag){
            System.out.println("登陆成功");
        }else{
            System.out.println("用户名或密码错误,请重新输入");
        }
    }

    public boolean login(String user, String password){
        if (user == null || password == null){
            return false;
        }
        String sql = "select * from user where username='"+user+"' and password='"+password+"' ";
        System.out.println(sql);
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(rs, stmt, conn);
        }
        return false;
    }
}

 

运行结果:

Exception in thread "main" java.lang.NullPointerException
	at main.JdbcSQL.main(JdbcSQL.java:12)

Process finished with exit code 1
 

产生out文件夹:

方式一:Xxx.class.getClassLoader().getResource

注意此方法路径中不能包含中文!!!!!

JDBCUtils核心配置jdbc.properties代码:

//方式1 Xxx.class.getClassLoader().getResource 
String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
System.out.println(path);
pro.load(new FileReader(path));

在E:\Test\src\jdbc.properties创建文件

jdbc.properties

url=jdbc:mysql:///db1
user=root
password=root
driver=com.mysql.jdbc.Driver

 

运行结果:

/E:/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
/E:/Test/out/production/Test/jdbc.properties
登陆成功

Process finished with exit code 0

注意:

1.其实运行程序,程序会将E:\Test\src\jdbc.properties文件复制到E:\Test\out\production\Test\jdbc.properties,而实际起作用是E:\Test\out\production\Test\jdbc.properties文件,也可以直接在E:\Test\out\production\Test中创建jdbc.properties文件。

 

2.使用方式一,路径中不能有中文

jdbc.properties文件绝对路径为E:\测试\Test\src\jdbc.properties

读取的路径为/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties出现FileNotFoundException错误

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties
java.io.FileNotFoundException: E:\%e6%b5%8b%e8%af%95\Test\out\production\Test\jdbc.properties (系统找不到指定的路径。)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
	at java.base/java.io.FileReader.<init>(FileReader.java:60)
	at main.JDBCUtils.<clinit>(JDBCUtils.java:21)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
java.sql.SQLException: The url cannot be null
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:660)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
	at main.JDBCUtils.getConnection(JDBCUtils.java:49)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
用户名或密码错误,请重新输入

Process finished with exit code 0

 

方式二:Xxx.class.getClassLoader().getResourceAsStream

注意此方法路径中可以包含中文!

JDBCUtils核心配置jdbc.properties代码

//方式2 Xxx.class.getClassLoader().getResourceAsStream
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
pro.load(in);

运行结果:

在E:\Test\src\jdbc.properties创建文件jdbc.properties

url=jdbc:mysql:///db1
user=root
password=root
driver=com.mysql.jdbc.Driver

 

运行结果:

/E:/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陆成功

Process finished with exit code 0

 

拓展:路径中可以包含中文,jdbc.properties文件绝对路径为E:\测试\Test\src\jdbc.properties

运行结果:

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陆成功

Process finished with exit code 0

 

 

方式三: Xxx.class.getResource

注意此方式路径中不能包含中文!!!

JDBCUtils核心配置jdbc.properties代码

 //方式3 Xxx.class.getResource
String path = JDBCUtils.class.getResource("jdbc.properties").getPath();
pro.load(new FileReader(path));

 

运行出错:

/E:/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class main.JDBCUtils
	at main.JdbcSQL.login(JdbcSQL.java:45)
	at main.JdbcSQL.main(JdbcSQL.java:20)

Process finished with exit code 1

 

在E:\Test\src\main\jdbc.properties创建文件:

运行结果:

/E:/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陆成功

Process finished with exit code 0

 

拓展:

此方法中路径不能包含中文!

jdbc.properties文件绝对路径为E:\测试\Test\src\jdbc.properties

读取的路径为/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties出现FileNotFoundException错误

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
java.io.FileNotFoundException: E:\%e6%b5%8b%e8%af%95\Test\out\production\Test\main\jdbc.properties (系统找不到指定的路径。)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
	at java.base/java.io.FileReader.<init>(FileReader.java:60)
	at main.JDBCUtils.<clinit>(JDBCUtils.java:28)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
java.sql.SQLException: The url cannot be null
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:660)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
	at main.JDBCUtils.getConnection(JDBCUtils.java:49)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
用户名或密码错误,请重新输入

Process finished with exit code 0

 

方式四:Xxx.class.getResourceAsStream

注意此方法路径中可以包含中文!!

JDBCUtils核心配置jdbc.properties代码

//方式4 Xxx.class.getResourceAsStream
InputStream in = JdbcSQL.class.getResourceAsStream("jdbc.properties");
pro.load(in);

运行结果:

/E:/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陆成功

Process finished with exit code 0

 

拓展:

验证路径中可以包含中文

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陆成功

Process finished with exit code 0

 

 

方式五:resources/jdbc.properties

JDBCUtils核心配置jdbc.properties代码

//方式5 resources/jdbc.properties
pro.load(new FileInputStream("resources/jdbc.properties"));

 

此方法需要在工程目录结构中创建resources文件夹并设置为Resources Root ,并在resources/jdbc.properties创建文件

 

总结规律:

1.Xxx.class.getClassLoader().getResource ,Xxx.class.getClassLoader().getResourceAsStream需要将xxx.properties文件放在工程的src文件夹下,如以上实验放置在E:\Test\src文件夹下;

2.Xxx.class.getResource, Xxx.class.getResourceAsStream要将xxx.properties文件放在工程中Xxx.class文件的同一目录下,如以上实验放置在E:\Test\src\main文件夹下;

3.Xxx.class.getClassLoader().getResource , Xxx.class.getResource 方式中xxx.properties文件的路径不能包含中文,不然会报NoClassDefFoundError 错误。

 

4.Xxx.class.getClassLoader().getResourceAsStream,Xxx.class.getResourceAsStream方式中xxx.properties文件的路径可以包含中文。

 

5.resources/jdbc.properties方式需要创建resources文件夹并设置为Resources Root ,并在resources/jdbc.properties创建文件。

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值