心得:
容易出现NullPointerException异常,有下列情况:
注意事项:jdbc.properties文件路径问题,可以自己动手写一个properties的类文件,进行测试一下,调用Properties.load(in)方法时,应该行判断一下有没有读取到.,有则下一步.
Key的名称一定在相同.,
package jdbc.test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 读取jdbc.properties文件并连接数据库
* 关闭数据库连接
* 返回Connection的方法
*
* @author Administrator
*
*/
public class JDBCProperties {
private String classDriver;
private String url;
private String username;
private String password;
private Connection connection;
private Statement statement;
private ResultSet resultSet;
/**
* 创建一个空参构造函数加载配置文件 取得参数连接数据库
*
* @return Connection
* @throws IOException
* @throws ClassNotFoundException
*/
public JDBCProperties() throws IOException, ClassNotFoundException {
// 输入文件
//路径为当前Classpath的路径.
InputStream inputStream = JDBCProperties.class.getClass()
.getResourceAsStream("/jdbc.properties");
System.out.println(inputStream);
java.util.Properties properties = new java.util.Properties();
if (inputStream != null)
properties.load(inputStream);
// 根据Key取得配置文件中的值
classDriver = properties.getProperty("classDriver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
System.out.println(classDriver);
System.out.println(url);
System.out.println(username);
System.out.println(password);
// 加载类文件
Class.forName(classDriver);
}
/**
*
*
* @return
* @throws SQLException
*/
public java.sql.Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
/**
* 关闭数据库连接信息
*/
public void closeConnceiont() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
}
测试创建一个表
package jdbc.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestJdbc {
private static String sql = "create table test(id int)";
public static void main(String[] args) throws Exception {
JDBCProperties jdbcProperties = new JDBCProperties();
Connection connection = jdbcProperties.getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
ResultSet resultSet = statement.getResultSet();
if (resultSet != null) {
while (resultSet.next()) {
System.out.println(resultSet.getObject(1));
}
}
}
}
jdbc.properties文件
classDriver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=admin