我的java项目中有两个文件: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);
将语句对象分配给名为stmt
的局部变量,而不是具有相同名称的对象字段。更换此
Statement stmt = conn.createStatement();
有了这个:
this.stmt = conn.createStatement();
this
在这里没有必要,但在那里有它是一个很好的做法。