import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Properties;
public class PreparedStatementTest {
private String driver;
private String url;
private String user;
private String pass;
public void initParam(String paramFile)throws Exception{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty(driver);
url = props.getProperty(url);
user = props.getProperty(user);
pass = props.getProperty(pass);
Class.forName(driver);
}
public void insertUseStatement()throws Exception{
long start = System.currentTimeMillis();
try(
Connection conn= DriverManager.getConnection(url,user,pass);
Statement stmt = conn.createStatement()
){
for(int i = 0;i < 100; i++){
stmt.executeUpdate("insert into student_id values('姓名"+i+"','姓名"+i+"')");
}
System.out.println("使用Statement费时:"+(System.currentTimeMillis()-start));
}
}
public void insertUsePrepare() throws Exception{
long start = System.currentTimeMillis();
try(
Connection conn = DriverManager.getConnection(url,user,pass);
PreparedStatement pstmt = conn.prepareStatement("insert into student_id values(?,?)")
){
for(int i = 0;i < 100;i++){
pstmt.setString(i,"姓名"+i);
pstmt.executeUpdate();
}
System.out.println("使用PreparedStatement费时:"+(System.currentTimeMillis()-start));
}
}
public static void main(String[] args)throws Exception{
PreparedStatementTest pt = new PreparedStatementTest();
pt.initParam("mysql.ini");
pt.insertUseStatement();
pt.insertUsePrepare();
}
}
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.hash(Hashtable.java:239)
at java.util.Hashtable.get(Hashtable.java:434)
at java.util.Properties.getProperty(Properties.java:951)
at PreparedStatementTest.initParam(PreparedStatementTest.java:17)
at PreparedStatementTest.main(PreparedStatementTest.java:54)
student_id表示存在的,怎么就报空指针呢?
PreparedStatementTest.java:17行 和 PreparedStatementTest.java:54行有错,这两行代码贴出来看看。
mysql.ini是第54行,是一个属性文件,里面有driver,url,user,pass
确定连接数据库成功吗?
先确定空指针 到底是什么为空,是不是连接数据库不成功引起的。