I am currently entering data into a database from a calendar, and I have realized that any new entry I input turns out to be null. All of the data entered is of the same dataype as the column, and I’m confused to as how this is happening. None of the values I’m inputting are null or empty. I have debugged and watched the values to know that.
public static void insertEvent(string date, string title, string eventLocation, string detailsShort, string detailsLong, DateTime startTime, DateTime endTime, DateTime entered, string enteredBy)
{
try
{
string queryString = "INSERT INTO cor(cal_date,event_title,event_location,details_short,details_long,time_start,time_end,entered,entered_by) VALUES (cal_date=cal_date, event_title=event_title, event_location=event_location, details_short=details_short, details_long=details_long,time_start=time_start, time_end=time_end, entered=entered, entered_by=entered_by)";
OdbcConnection conn = new OdbcConnection(MyConString);
conn.Open();
OdbcCommand command = new OdbcCommand(queryString, conn);
command.Parameters.Add("cal_date", OdbcType.DateTime, 30).Value = date;
command.Parameters.Add("event_title", OdbcType.VarChar, 100).Value = title;
command.Parameters.Add("event_location", OdbcType.VarChar, 100).Value = eventLocation;
command.Parameters.Add("details_short", OdbcType.VarChar, 300).Value = detailsShort;
command.Parameters.Add("details_long", OdbcType.VarChar, 300).Value = detailsLong;
command.Parameters.Add("time_start", OdbcType.DateTime, 30).Value = startTime;
command.Parameters.Add("time_end", OdbcType.DateTime, 30).Value = endTime;
command.Parameters.Add("entered", OdbcType.DateTime, 30).Value = entered;
command.Parameters.Add("entered_by", OdbcType.VarChar, 30).Value = enteredBy;
command.ExecuteNonQuery();
conn.Close();
}
catch (Exception)
{
}
}
The problem is the expression
cal_date=cal_date(and similar expressions for every column).As you’re inserting a new row, there is no value for any column yet. So any reference to the column is NULL. The expression NULL=NULL also yields NULL. So you’re not inserting values, you’re inserting NULL expressions for all columns.
If you change the expression to
cal_date=@cal_dateit doesn’t fix the problem. You’re comparing the current value forcal_date(which is NULL) to the value of the parameter@cal_date. An expression likeNULL=<anything>always yields NULL.You should just use parameters, not expressions:
update: Read the example code in “Pass Parameters to OdbcCommand“. That example shows using
?placeholders as @ZombieHunter’s answer recommends — not named parameter placeholders. However, when callingParameters.Add(), somehow one uses the named parameter with@prefix. Go figure.