I'm trying to write a query to my database. When I originally wrote it I didn't use parameters, I am now trying to do so But I am getting a Mysql Error now.
Column count doesn't match value at row1
Which in my 1st column I have an auto Incremented number labeled as "ID" Which I do not believe I have to add to the query because of the auto increment..
This is the newly written code:
MySqlConnection conn = new MySqlConnection(dbConnection);
string Query = "INSERT INTO tasklist.tasks (TaskName, AssignedTo, StartDate, EndDate, Description, DirPath, Completed) VALUES (?TaskName),(?AssignedTo),(?StartDate),(?EndDate),(?Description),(?DirPath),(?Completed);";
MySqlCommand insertCommand = new MySqlCommand(Query, conn);
conn.Open();
insertCommand.Parameters.AddWithValue("?TaskName", txtTaskName.Text);
insertCommand.Parameters.AddWithValue("?AssignedTo", txtAssignTo.Text);
insertCommand.Parameters.AddWithValue("?StartDate", txtdateStart.Value.ToString("yyyy-M-d"));
insertCommand.Parameters.AddWithValue("?EndDate", txtDateEnd.Value.ToString("yyyy-M-d"));
insertCommand.Parameters.AddWithValue("?Description", txtTaskDescription.Text);
insertCommand.Parameters.AddWithValue("?DirPath", txtDirPath.Text);
insertCommand.Parameters.AddWithValue("?Completed",("0"));
insertCommand.ExecuteNonQuery();
conn.Close();
Remember the previous way without parameters worked... however with parameters does not work. What exactly am I doing wrong here? Any help would be greatly appreciated.
Talk2:
When using .add VS states that .add is deprecated and to use .AddWithValue
Talk3:
Look more closely - it is the .Add(object, object) form that is deprecated. Parameters.Add("@p1", MySqlDbType.Foo).Value = varBar; Specifying the datatype prevents any misunderstanding or unwanted type conversions
Talk4:
I see, thanks for the info
Solutions1
Use only one pair of parentheses around all parameters
INSERT INTO tasklist.tasks (TaskName, AssignedTo, StartDate, EndDate, Description, DirPath, Completed)
VALUES (?TaskName, ?AssignedTo, ?StartDate, ?EndDate, ?Description, ?DirPath, ?Completed)
Talk1:
, note that all the values per row you're inserting are within () parentheses, not each value. If you were inserting 2 rows, the second set of values would also be contained, together, in another set.
Talk2:
Yeah, I just figured it out right before I came back to check. This is what I did. string Query = "INSERT INTO tasklist.tasks (TaskName, AssignedTo, StartDate, EndDate, Description, DirPath, Completed) VALUES ((?TaskName), (?AssignedTo), (?StartDate), (?EndDate), (?Description), (?DirPath), (?Completed));"; which fixed it
Talk3:
Sorry, I code a lot in SQF for A game called Arma 3. Redundant parentheses are common and needed in the language... Force of habit I guess. Will fix. Thanks for the constructive criticism.