import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class TestDML2 {
public static void main(String[] args) {
System.out.println("请输入要插入的数据,格式为deptno dname loc");
Scanner scanner=new Scanner(System.in);
int deptno=scanner.nextInt();
String dname=scanner.next();
String loc=scanner.next();
System.out.println("insert into dept values("+deptno+",'"+dname+"','"+loc+"')");
insert(deptno,dname,loc);
}
private static void insert(int deptno, String dname, String loc) {
Connection conn=null;
Statement stmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata", "root", "yj1039");
stmt.executeUpdate("insert into dept values("+deptno+",'"+dname+"','"+loc+"')");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally{
try{
if(stmt!=null){
stmt.close();
stmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
请输入要插入的数据,格式为deptno dname loc
12
a
b
insert into dept values(12,'a','b')
Exception in thread "main" java.lang.NullPointerException
at TestDML2.insert(TestDML2.java:25)
at TestDML2.main(TestDML2.java:15)
------最佳解决方案--------------------------------------------------------
你有没有创建Statement对象
Statement stmt=null;
这样就直接stmt.executeUpdate
当然会空指针了!
stmt=conn.createStatement();
创建了在去使用它!
声明一个变量之后、必须用赋值语句对变量进行显式初始化它、然后再去使用!