我的java项目中有2个文件:MysqlConnect和Main。 我想从Main类运行查询。这可能吗?
这是MysqlConnect文件:
public class MysqlConnect {
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public Statement stmt;
public String query = "";
public int rs;
public void crearedatabase() {
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
// System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Baza de date nu a fost creata");
}
}
public void executeSql() {
try {
rs = stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println("Mysql Error");
}
}
}
这是 主文件 :
public class Main {
public static void main(String[] args) throws SQLException
{
MysqlConnect sqlconnect = new MysqlConnect();
sqlconnect.crearedatabase();
sqlconnect.query="INSERT INTO `jdbctutorial`.`persons` (`id`, `nume`, `prenume`, `data`) VALUES (NULL, 'xxxx', 'xxxx', '1990-12-12');";
sqlconnect.executeSql();
}
}
错误(异常)位于try / catch
的MysqConnection上rs = stmt.executeUpdate(query);
答案 0 :(得分:1)
将语句对象分配给名为stmt
的局部变量,而不是具有相同名称的对象字段。
替换此
Statement stmt = conn.createStatement();
有了这个:
this.stmt = conn.createStatement();
this
在这里不是必需的,但将它放在那里是一种很好的做法。