C#将数据添加到sql表 [英] C# add data to sql table

查看:83
本文介绍了C#将数据添加到sql表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

我有一个表单,用户可以添加一个新客户端,然后单击按钮即可将数据插入数据库.

这是我的代码,效果很好

Hey,

I have a form that user can add a new client and it inserts data into database by a button click.

this is my code that worked perfectly

private void button1_Click(object sender, EventArgs e)
{

    string sqlText = "SELECT MAX(customerName) FROM Customer";

    SqlConnection sqlConn = new SqlConnection(@"Data Source=Admin-PC\SQLEXPRESS;Initial Catalog=Couriers;Integrated Security=True");

    SqlCommand command = new SqlCommand(sqlText, sqlConn);


    SqlDataAdapter da = new SqlDataAdapter();
    da.InsertCommand = new SqlCommand("INSERT INTO Customer VALUES(@customerName,@CustomerAddress,@CustomerContact,@VatNo)", sqlConn);
    da.InsertCommand.Parameters.Add("@customerName", SqlDbType.VarChar).Value = textBox4.Text;
    da.InsertCommand.Parameters.Add("@CustomerAddress", SqlDbType.VarChar).Value = textBox2.Text;
    da.InsertCommand.Parameters.Add("@CustomerContact", SqlDbType.Int).Value = textBox3.Text;
    da.InsertCommand.Parameters.Add("@VatNo", SqlDbType.Int).Value = textBox5.Text;
    
    sqlConn.Open();
    da.InsertCommand.ExecuteNonQuery();
    sqlConn.Close();
    MessageBox.Show("Client Successfully added");
    this.Close();

}



现在,我将CustomerId添加到我的SQL表中,并且此代码有问题.
必须自动生成customerId,不要用户输入id,但是现在代码错误



Now i added CustomerId into my SQL table and having problems with this code.
The customerId must be generated automatically dont want user to input id, but now the code is wrong

推荐答案

在您的表(Sql Table)中,截断所有数据(如果需要保持备份).现在,更改列CustomerId 并将其设置为IDENTITY.在那之后,您不要在值列中插入值.
试试这个:
In your table(Sql Table), truncate your all data (If required keep a backup). Now, alter your column CustomerId and set it as IDENTITY. After that you don''t suppose to insert the value in identity column.
Try this:
alter table table1 add col3 int identity(1,1)


请参考 [


Refer this[^] for more information on identity columns.


--Amit


这篇关于C#将数据添加到sql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆