本文介绍了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
推荐答案
alter table table1 add col3 int identity(1,1)
请参考此 [ ^ ],以获取有关标识列的更多信息.
--Amit
Refer this[^] for more information on identity columns.
--Amit
这篇关于C#将数据添加到sql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!