我正在尝试让我的代码顺利运行但是在第一次插入之后,当表存在时,我总是在创建fisr表并插入数据后出现此错误com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'bus' already exists
此错误发生?!我想只检查表是否存在,如果没有创建tabe并插入数据,如果是,只需更新数据。
数据库类:
package org.busTracker.serverSide;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
public void connection() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("jar works :) ");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insertData(String mac, int route, float latitude,
float longitude) {
connection();
String host = "jdbc:mysql://localhost/busTracker";
String user = "root";
String password = "";
try {
Connection con = DriverManager.getConnection(host, user, password);
// Create a statement
Statement stt = con.createStatement();
// Check whether table exists.
boolean rest = stt.execute("SHOW TABLES like 'bus' ");
if (rest) {
PreparedStatement prep = con
.prepareStatement("REPLACE INTO bus(mac, route, latitude, longitude)"
+ "VALUES( ?, ?, ? , ? )");
prep.setString(1, mac);
prep.setInt(2, route);
prep.setFloat(3, latitude);
prep.setFloat(4, longitude);
prep.executeQuery();
} else {
// Create bus table
stt.execute("CREATE TABLE bus"
+ "(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
+ "mac VARCHAR(30) NOT NULL UNIQUE,"
+ "route int(11) NOT NULL,"
+ "latitude FLOAT(10,6) NOT NULL,"
+ "longitude FLOAT(10,6) NOT NULL,"
+ "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
PreparedStatement prep = con
.prepareStatement("REPLACE INTO bus(mac, route, latitude, longitude)"
+ "VALUES( ?, ?, ? , ? )");
prep.setString(1, mac);
prep.setInt(2, route);
prep.setFloat(3, latitude);
prep.setFloat(4, longitude);
prep.executeQuery();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:4)
您可能希望使用CREATE TABLE IF NOT EXISTS语法
https://dev.mysql.com/doc/refman/5.5/en/create-table.html
这样可以避免这种错误
但我会检查是否
{{1}}
正常工作,您可能会得到错误的结果并执行错误的操作