JAVA JDBC编程 DBUtil 报错 Exception in thread "main" java.lang.NullPointerException

Exception in thread “main” java.lang.NullPointerException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at DBUtil.getConnection(DBUtil.java:29)
at DBUtil.main(DBUtil.java:104)

DBUtil 29行:Class.forName(driver);

DBUtil 104行:System.out.println(db.getConnection());

错误原因:
在mysql.properties 每项的前面加上了jdbc.
jdbc.driver…去掉了就好了

//mysql.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/student0010?useUnicode=true&characterEncoding=utf8&useSSL=false
user=root
password=123456

JAVA JDBC编程 DBUtil 报错 Exception in thread

贴上其他代码:

//DBUtil.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
	
	private Connection conn;
	private PreparedStatement preStmt;
	private ResultSet rs;

	public static Connection getConnection() throws SQLException {
		Properties p=new Properties();
		File file=new File("config"+File.separator+"mysql.properties");
		try {
			p.load(new FileInputStream(file));
			String user=p.getProperty("user");
			String password=p.getProperty("password");
			String driver=p.getProperty("driver");
			String url=p.getProperty("url");
			
			Class.forName(driver);
			
			return DriverManager.getConnection(url, user, password);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SQLException("加载配置文件失败!");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SQLException("数据库驱动程序未找到!");
		}
		
	}
	
	
	public void closeAll() {
		try {
			if(null!=rs)
				rs.close();
			if(null!=preStmt)
				preStmt.close();
			if(null!=conn)
				conn.close();
			
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public ResultSet executeQuery(String sql, Object...params)throws Exception
	{
		conn=this.getConnection();
		if(null==sql)
			return null;
		
		preStmt=conn.prepareStatement(sql);
		if(null!=params && params.length>0) {
			for(int i=0;i0) {
			for(int i=0;i

书上说要写config.java,我没写也可以

//config.java
import java.io.FileInputStream;
import java.util.Properties;

public class config {
	private static Properties p=null;
	static {
		try {
			p=new Properties();
			p.load(new FileInputStream("config/mysql.properties"));
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static String getValue(String key) {
		return p.get(key).toString();
	}
}

你可能感兴趣的:(java)