简体   繁体   中英

Error with adding records to SQL Server database (nvarchar)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM