从Web表单中插入表中的值 [英] inserting values in table from a web form
本文介绍了从Web表单中插入表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个包含4个字段的Employeetable表。我想在表中插入值。
我的代码如下:
i have created a table Employeetable that have 4 fields. I want to insert the value in table .
my code is as follows:
SqlConnection connection1 = new SqlConnection();
SqlCommand Insert = new SqlCommand();
connection1.ConnectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\employeeDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
int a = Convert.ToInt32(txtEmpId.Text);
string b = txtEmpName.Text;
int c = Convert.ToInt32(txtSalary.Text);
string d = txtCity.Text;
Insert.CommandText = "INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d)";
Insert.Parameters.AddWithValue("@a", a);
Insert.Parameters.AddWithValue("@b", b);
Insert.Parameters.AddWithValue("@c", c);
Insert.Parameters.AddWithValue("@d", d);
Insert.Connection.Open();
Insert.ExecuteNonQuery();
Insert.Connection.Close();
Response.Write("you have succesfully inserted data");
当我在insert.connection.open()上调试它时,调试器指向对象引用未设置为对象的实例。哪里我错了?请帮我。谢谢。
also when i debug it on insert.connection.open() debugger points object refrence not set to instance of object. where i am wrong? please help me. Thanks.
推荐答案
您需要在SqlCommand上设置Connection属性。 http://msdn.microsoft.com/en-us/library/system。 data.sqlclient.sqlcommand.aspx [ ^ ]
例如,
You need to set the Connection property on your SqlCommand. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx[^]
For example,
Insert.Connection = connection1;
此处将此代码添加到您的项目中
here add this code to your project
Insert.CommandText = "INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d)";
Insert.connection= connection1; //name instance of your sql connection;
为什么要写两行?这里简单方法:
Why write two lines?? here the easy way:
string st="INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d";
//now declare your sql command
sql command insert= new sql command(st,connection1);
//or
sql command insert = new sql command("INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d", connection1)
你必须将你的命令与这种或那样的连接联系起来!!!
:)
有关检索访问的帮助
sql express
这篇关于从Web表单中插入表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文