Reputation: 41
I am trying to add records to a SQL Server database. The connection works fine for any other table except one.
This is my code:
private void saveCurrent()
{
try
// Save entry into the database.
{
string query = "INSERT INTO entries VALUES (@Date, @Tags, @Entry, @User)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("@Date", System.DateTime.Now.ToLongDateString());
command.Parameters.AddWithValue("@Tags", txtTags.Text);
command.Parameters.AddWithValue("@Entry", richEntryBox.Text);
command.Parameters.AddWithValue("@User", Form1.userName);
command.ExecuteNonQuery();
isDirty = false;
}
}
catch (Exception exception)
{
MessageBox.Show("There was an error saving this entry: " + exception.ToString());
}
The error is:
System.Data.SqlClient.SqlException (0x8-131904): Column name or number of supplied values does not match table definition.
All of the columns are of type nvarchar(50)
and nvarchar(MAX)
. I am trying to enter just text information, no binaries. The dataset shows that the table has a "photos" column, but it can be null and I'm not using it (for some reason, I cannot get VS2017 to delete that column). I have altered the dataset to not include the "photos" field, but still receiving the error. Any push to the solution would be appreciated. A snap of the dataset is included here.
My dataset, in which I've removed the photos column:
--S
Upvotes: 0
Views: 115
Reputation: 1596
If your database still has the photos
field, you'll need to specify the columns for insertion explicitly.
So change your insert to:
string query = "INSERT INTO entries (date, tags, entry, user) VALUES (@Date, @Tags, @Entry, @User)";
In general, you want to be explicit with your insertions. What would happen if someone added a column after tags and before entry in the database? This would break your code.
Upvotes: 3