您好我在Java中使用MySQL时遇到错误。每当我尝试插入到我的表中时(我在下面运行“testOne”时),我一直收到这个未知列错误。
public static void sendMessage(String username, String recipientName, String message, String title) {
DateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
Date date = new Date();
String stringDate = dateFormat.format(date);
String query = "INSERT INTO messages" + " (fromUser, toUser, message, title, dateCreated) VALUES ('" +
username + "', '" + recipientName + "', '" + message + "', '" + title + "', '" + stringDate + "')";
DBConnection.getInstance().executeQuery(query);
}
public void testOne(){
Message.sendMessage("user1", "user2", "hows it going", "hi");
}
CREATE TABLE messages (
id int AUTO_INCREMENT,
fromUser varchar(255),
toUser varchar(255),
mType int,
message TEXT,
title TEXT,
dateCreated varchar(255),
seen TINYINT(1),
quizID int,
PRIMARY KEY(pID)
);
public ResultSet executeQuery(String query){
ResultSet rs= null;
try {
java.sql.Statement stmt = connection.createStatement();
// this is the trick -- you need to pass different SQL to different methods
if (query.startsWith("SELECT")) {
rs = stmt.executeQuery(query);
} else if (query.startsWith("UPDATE") || query.startsWith("INSERT")
|| query.startsWith("DELETE")) {
stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
rs = stmt.getGeneratedKeys();
} else {
stmt.execute(query, Statement.RETURN_GENERATED_KEYS);
rs = stmt.getGeneratedKeys();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return rs;
}
public static DBConnection getInstance() {
if (instance == null)
instance = new DBConnection(DBConnection.rootDirectory);
return instance;
}
但每次运行测试时都会出现此错误 - “字段列表”中的“未知”列“消息” 请帮忙!!!
答案 0 :(得分:0)
您收到错误的是哪一列?我面临着类似的问题。我在值“字符串”之前和之后放置了空格,并且它运行良好。在你的情况下,尝试在逗号之前添加空格。