简体   繁体   中英

Mysql error on INSERT Unknown column in 'field list'

Hi I'm having an error using MySQL in Java. I keep getting this unknown column error everytime I try to insert into my table (when I run "testOne" below).

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;
}

But I get this error everytime I run the test- Unknown column 'message' in 'field list' Please help!!!

Which column are you getting the error? I was facing similar problem. I placed space before and after "," in values String and it worked out well. In your case try adding space before Comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM