当我运行此代码以连接到数据库并添加对象时
import java.sql.*;
import java.util.Scanner;
import java.sql.*;
import java.util.Scanner;
public class Driver {
public static void main(String [] args) {
try {
//Get connection to DB
Connection myConn = DriverManager.getConnection("jdbc:mysql://LocalHost:3306/interndata?useSSL=false" , "root" , "Starwars991211");
//Create a statement
Statement myStmt = myConn.createStatement();
Scanner scan = new Scanner(System.in);
int entryNum, citNum ;
String date, score ;
String keepGoing = "y";
while (keepGoing.equals("y") || keepGoing.equals("Y")){
System.out.println("Enter the id");
entryNum = scan.nextInt();
System.out.println("Enter the date");
date = scan.next();
System.out.println("Enter the citnum");
citNum = scan.nextInt();
System.out.println("Enter the score");
score = scan.next();
String sql = "INSERT INTO employee (EntryNumber, Date, ``CriterionNum, Score)" + " values (?, ?, ?, ?)";
PreparedStatement preparedStatement = myConn.prepareStatement(sql);
preparedStatement.setInt(1, entryNum);
preparedStatement.setString(2, date);
preparedStatement.setInt(3,citNum);
preparedStatement.setString(4, score);
preparedStatement.executeUpdate();
System.out.print("Another factorial? (y/n) ");
keepGoing = scan.next();
}
//Execute SQL query
ResultSet myRs = myStmt.executeQuery("select * from teacherexample");
//process result set
while (myRs.next()) {
System.out.println("ID: " + myRs.getInt("EntryNumber") + " Name: " + myRs.getString("Date") + ", " + myRs.getInt("CriterionNum") + " " + myRs.getString("Score"));
}
}
catch (Exception exc) {
exc.printStackTrace();
}
}
}
我收到此错误
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'interndata.employee' doesn't exist
internexample.employee
是在我更改名称之前 interndata.teacherexample
的名称。
我的问题是,即使代码中没有提及,为什么程序仍然尝试连接到不存在的旧数据库?
最佳答案
why is the program still trying to connect to the older database that does not exist
在您的 JDBC
字符串中,您已将数据库名称指定为 interndata
jdbc:mysql://LocalHost:3306/interndata
因此,以下任何查询 INSERT
或 SELECT
都将在 interndata
数据库上下文下执行。
所以,当您执行以下查询时
INSERT INTO employee ...
它将针对 interndata
数据库中的 employee
表执行。如果您想在不同的数据库上下文(即 internexample
)中执行上述查询。然后,您需要将 JDBC
字符串更改为
jdbc:mysql://LocalHost:3306/internexample
关于java - JDBC 找不到正确的 MySql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693245/