简体   繁体   中英

Insert a record in table fails everytime

I have a database connection where i insert data into the table having 2 columns ie id , first_name , last_name . Following is the code:

    private void Insert_Click(object sender, EventArgs e)
    {
        try
        {

            String query = "INSERT INTO  data_table (first_name,last_name) VALUES (@f_name,@l_name)";

            using (SqlConnection connection1 = new SqlConnection(
                                      Properties.Settings.Default.DatabaseConnection))

            using (SqlCommand insertCommand = new SqlCommand(query, connection1))
            {
                //a shorter syntax to adding parameters
              //  insertCommand.Parameters.Add("@id", SqlDbType.Int).Value = 1;
                insertCommand.Parameters.Add("@f_name", SqlDbType.NChar).Value = "JAVED";

                insertCommand.Parameters.Add("@l_name", SqlDbType.NChar).Value = "GHAMJN";

                //make sure you open and close(after executing) the connection
                connection1.Open();
                insertCommand.ExecuteNonQuery();
                connection1.Close();

                MessageBox.Show("Record inserted. Please check your table data. :)");

            }

        }
        catch (Exception err)
        {

            MessageBox.Show(err.Message);

        }
  }

Following is T-SQL script:

CREATE TABLE [dbo].[data_table] (
[Id]         INT        NOT NULL IDENTITY,
[first_name] NCHAR (10) NULL,
[last_name]  NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
 );

The issue is created by id: I have set it auto-increment. When i click insert button a MessageBox pops saying:

Cannot insert the value NULL into column 'Id',table 'C:\\Users.......\\Database1.MDF.dbo.data_table;column doesn't allows null.INSERT fails

Add identity seed and increment values to your table...

CREATE TABLE [dbo].[data_table] (
[Id]         INT        NOT NULL IDENTITY(1,1),
[first_name] NCHAR (10) NULL,
[last_name]  NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
 );

Your Id field should be modified as shown below

在此处输入图片说明

try this . The behaviour of Identity Columns can be selectively enabled or disabled with this statement.

If your Identity Column is configured correctly, then this is the only logical explanation for it not behaving as expected

SET IDENTITY_INSERT [dbo].[data_table] ON;


However, it is more likely that your assertion of correctness is flawed and you have not configured the Identity Column correctly.

删除该表以及旧表的所有旧副本,并使用建议的Identity(1,1)创建一个新表解决了该问题

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