MySQL Java数据插入错误

时间:2015-01-21 01:20:32

标签: java mysql sql

我试图连接到mySQL数据库并在我的Java应用程序中的3列osName,version,notes上执行Insert。以下教程是http://alvinalexander.com/java/java-mysql-insert-example-preparedstatement。任何输入或评论都是有帮助的。这是我的数据库信息 -

CREATE TABLE oslogentry(    osName VARCHAR(10)NOT NULL,    version VARCHAR(10)NOT NULL,    notes VARCHAR(20)NOT NULL,    主要关键(osName) )ENGINE = InnoDB;

 package com.tutorialspoint.struts2;

 import java.sql.*;

 import com.opensymphony.xwork2.ActionSupport;

 public class HelloWorldAction extends ActionSupport{
private String osName;
private String version;
private String notes;

public String execute() throws Exception {
    return "success";
 }
{

        try
        {
            // created a datbase connection
            String myDriver = "org.gjt.mm.mysql.Driver";
            String myURL = "jdbc:mysql://localhost/HelloWorld";
            Class.forName(myDriver);
            Connection conn = DriverManager.getConnection(myURL, "root", "");

            //insert statement

            String query = "INSERT INTO oslog.entry (osName,version,notes " + 
            "values osName, version, notes";

            //mysql insert preparedstatement

            PreparedStatement preparedStmt = conn.prepareStatement(query);
            preparedStmt.setString(1, osName);
            preparedStmt.setString(2, version);
            preparedStmt.setString(3, notes);
            //excute the preparedstatement
            preparedStmt.execute();
            conn.close();

        }
        catch(Exception e)
        {
            System.err.println("Got an Exception!");
            System.err.println(e.getMessage());
        }


}




    public String getOsName() {
    return osName;
}
public void setOsName(String osName) {
    this.osName = osName;
}
public String getVersion() {
    return version;
}
public void setVersion(String version) {
    this.version = version;
}
public String getNotes() {
    return notes;
}
public void setNotes(String notes) {
    this.notes = notes;
}

public void validate()
{
    if (osName == null || osName.trim().equals(""))
    { 
        addFieldError("osName","The OS name is required");
    }
    if (version == null || version.trim().equals(""))
    {
        addFieldError("version","The OS version is required");
    }
}
}

2 个答案:

答案 0 :(得分:2)

我发现你正在使用PreparedStatement 您需要更改query字符串:

 String query = "INSERT INTO oslog.entry (osName,version,notes " + 
        "values osName, version, notes";

 String query = "INSERT INTO oslog.entry(osName,version,notes) " + 
        "values (?, ?, ?)";

答案 1 :(得分:2)

您正在使用PreparedStatement,因此您的查询应该有占位符。试试这个:

String query = "INSERT INTO oslog.entry (osName,version,notes) " + 
            "values (?, ?, ?)";