MySQL ODBC Parameter issue

2019-08-09 14:32发布

问题:

Okay, so I'm getting a weird error with this function. It's saying:

Exception Details: System.Data.Odbc.OdbcException: ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.27-community-nt]Column 'CommentNumber' cannot be null

But I can verify that the variable commentnumber is indeed getting a value. If I put a Response.Write right before the

command.Parameters.Add("@CommentNumber", commentnumber);"

line I get 1 returned (which is correct).

public string commenter(string commentnumber, string postnumber, string commentname, string commentemail, string comment) {
OdbcConnection connection = new OdbcConnection();
connection.ConnectionString = "server=<address>;"
+ "database=<database>;"
+ "uid=<username>;"
+ "password=<password>;"
+ "DRIVER={MySQL ODBC 5.1 Driver}";
string CommandText = "INSERT INTO Comments (CommentNumber, PostNumber, Name, Email, PostTime, Comment) VALUES (@CommentNumber, @PostNumber, @Name, @Email, @PostTime, @Comment)";
connection.Open();
try {
    OdbcCommand command = new OdbcCommand(CommandText, connection);
    command.Parameters.Add("@CommentNumber", commentnumber);
    command.Parameters.Add("@PostNumber", postnumber);
    command.Parameters.Add("@Name", commentname);
    command.Parameters.Add("@Email", commentemail);
    command.Parameters.Add("@PostTime", DateTime.Now);
    command.Parameters.Add("@Comment", comment);
    command.ExecuteNonQuery();
    command.Dispose();
    command = null;
}
catch(Exception ex) {
//      Response.Write("There's been a problem. Please contact technical support.");
    throw new Exception(ex.ToString(), ex);
    Response.End();
}
finally {
    connection.Close();
}
return "Success!";

}

回答1:

ODBC uses ? for placholders. Since you're using @CommandNumber in the raw sql string, it's actually being interpreted by MySQL as an undefined server-side variable, hence the "cannot be null" error.



回答2:

The second parameter is the OdbcType, not the value. Try using .AddWithValue()



回答3:

What type is the field CommentNumber?. Specifies the type of the parameter to add command.Parameters