连接数据库建表中出现如下报错,学生刚入门,求大神帮忙看一下原因
Exception in thread "main" java.lang.NullPointerException
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1214)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1205)
at Week4.One.main(One.java:29)
代码如下
package Week4;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class One {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/hello";
Connection conn = DriverManager.getConnection(url, "root", "");
Statement stat = conn.createStatement();
stat.close();
conn.close();
stat.executeUpdate("create table oe_class("
+ "clid int not null,"
+ "coid int not null,"
+ "seeid int not null,"
+ "uname int not null,"
+ "sesid int not null,"
+"clweek int not null,"
+"primary key (clid);"
+ ")");
stat.executeUpdate("create table oe_course("
+ "coid int not null,"
+ "coname varchar(20) not null,"
+"primary key (coid);"
+ ")");
简单点,就是将stat.close(); conn.close();放到最后。所有 stat.executeUpdate()后面。primary key (clid);后面分号删掉。
执行 executeUpdate 方法要加 try/catch
stat.close()
conn.close() 关闭连接放到finally
添加
try{
Class.forName("com.mysql.jdbc.Driver");
.....
stat.executeUpdate("create table oe_course("
+ "coid int not null,"
+ "coname varchar(20) not null,"
+"primary key (coid);"
+ ")");
}catch (){
......
}finally{
吧stat.close() 和conn.close() 放到finally 中
}
异常已经报出来了,是空指针异常,意思就是DriverManager并未成功获取Connection对象,所以conn 是null,
后面 的conn.createStatement()语句就会报nullpointer异常,
1. 添加数据库密码,DriverManager.getConnection(url, "root", "")
2. 检查驱动是否添加到类路径
一般的,finally块中用于释放资源,断开连接,尽量使用try ··· catch····· finally语句块:
try为你要进行的操作,一般的如过出现错误需要用catch进行捕获,最后不管成果功与否都需要将资源释放。
stat.close();
conn.close();
你过早的关闭了连接,造成了空指针异常,站讯不到对应的对象。
可以参考:
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/hello";
Connection conn = DriverManager.getConnection(url, "root", "");
Statement stat = conn.createStatement();
····························
}catch(Exception e){
e.printStackTrace();
}fianlly{
stat.close();
conn.close();
}
空指针异常啊,楼上已经说的很好了
把
stat.close();
conn.close();
这两行放到最后。