将sql语句从java推送到数据库,executeUpdate()返回NullPointerException
因此,我试图将信息从java应用程序存储到数据库中,但我遇到了这样的错误:“AWT-EventQueue-0”java.lang.NullPointerException,我一生都找不到原因。 我曾经尝试过更改变量的名称,也尝试过使用“PreparedStation”。但迄今为止,一切都没有起作用将sql语句从java推送到数据库,executeUpdate()返回NullPointerException,java,mysql,Java,Mysql,因此,我试图将信息从java应用程序存储到数据库中,但我遇到了这样的错误:“AWT-EventQueue-0”java.lang.NullPointerException,我一生都找不到原因。 我曾经尝试过更改变量的名称,也尝试过使用“PreparedStation”。但迄今为止,一切都没有起作用 public class Db { public static final String DRIVER ="com.mysql.jbdc.Driver"; public static final S
public class Db {
public static final String DRIVER ="com.mysql.jbdc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/oving8";
public static final String USER = "root";
public static final String PW = "";
private static Connection kobling;
private static Statement settOppStatment(){
try {
Class.forName(DRIVER);
Connection tilkobling = DriverManager.getConnection(URL, USER, PW);
return tilkobling.createStatement();
} catch (ClassNotFoundException e) {
System.out.println("Can not find the class in");
} catch (SQLException e) {
System.out.println("Can not connect to database");
}
return null;
}
public static void skrivEnhetTilDB(Enhet enhet){
Statement st = settOppStatment();
String ID = Enhet.getId();
String Navn = Enhet.getNavn();
String sqlEnhet = null;
if (enhet != null){
sqlEnhet = "INSERT INTO enhet VALUES('"+ ID + "','" + Navn + "');";
};
System.out.println(sqlEnhet);
try {
st.executeUpdate(sqlEnhet); <---- Line 123
} catch (SQLException e) {
System.out.println("This unit is already registerd");
}
try {
st.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
如果您得到这些异常中的任何一个,下面的代码将返回null。在这种情况下,由于您有sysout,您应该在控制台或日志文件中看到这些消息 您还可以使用调试器逐行检查正在发生的情况
private static Statement settOppStatment(){
try {
Class.forName(DRIVER);
Connection tilkobling = DriverManager.getConnection(URL, USER, PW);
return tilkobling.createStatement();
} catch (ClassNotFoundException e) {
System.out.println("Can not find the class in");
} catch (SQLException e) {
System.out.println("Can not connect to database");
}
return null;
}
经过五个小时的工作,我发现这是一个拼写错误 之前: 公共静态最终字符串DRIVER=“com.mysql.jbdc.DRIVER” 之后:
public static final String DRIVER ="com.mysql.jdbc.Driver";
您的
setToppstation
方法必须返回null。setToppstation()
返回了null
,因为在建立连接和创建语句时出现了一些错误。请尝试调试代码并检查您输入的密码、登录名、url和驱动程序是否正确-看起来您没有连接到数据库我也尝试过,我无法真正理解其中的任何内容,因此这没有多大帮助。您是否在控制台或日志文件上看到“找不到中的类”或“无法连接到数据库”?不,它只返回sysout和stacktrace。您所说的返回sysout是什么意思?Db.java第123行是什么代码?我在代码st.executeUpdate(sqlEnhet)中标记了该行;
public static final String DRIVER ="com.mysql.jdbc.Driver";