[英]Insert data into SQL Server from C# code
I have a table student
( id, name
). 我有一个表
student
( id, name
)。 Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. 然后我有一个文本框,为了输入名称,当点击提交按钮时,它会将数据插入到数据库中。 So how can I insert only to name, not id because id is auto increment?
那么如何只插入名称,而不是id,因为id是自动增量?
I tried this 我试过这个
insert into student(id, name) values(,name)
but it is not insert to my table. 但它不是插入我的表。
This is my code : 这是我的代码:
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id
column altogether, it will be populated automatically. 完全省略
id
列,它将自动填充。 To use your variable, you should parameterise your SQL query. 要使用变量,您应该参数化SQL查询。
string sql = "INSERT INTO student (name) values (@name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities. 您永远不应该通过构造包含输入值的SQL字符串来尝试这样做,因为这会将您的代码暴露给SQL注入漏洞。
You better use parameters when you insert data. 插入数据时最好使用参数。
try
{
string sql = "insert into student(name) values (@name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
您无需在第一部分中提及ID。
insert into student(name) values('name')
string sql = "INSERT INTO student (name) values (@name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = test;
cmd.ExecuteNonQuery();
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows: commands executed in command shell of mssql like: 我遇到了这个问题,在尝试了堆栈溢出后发现的各种解决方案之后,我可以总结一下这样的经验:在mssql的命令shell中执行的命令如:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or 要么
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt, 直接在mssql数据库提示符下输入时工作,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in: 但是当需要使用c#中的insert语句时,需要记住字符串需要在字符串周围附加一对单个quite,如:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this. 这里的问题是大多数人,像我一样,尝试使用<\\“>代替双引号<”>,这是在上面的命令行情况下实现的,而SQL执行器无法理解这个含义。
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation , where a string concatination looks like a feasible solution, like in: 即使在需要替换字符串的情况下,也要确保字符串被单引号包围,其中字符串连接看起来像一个可行的解决方案,如:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
Try the following query, 尝试以下查询,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. 当你插入数据时,SQL Server在内部自动增加id列,因为你说它是自动增量。 If it is not working, the u have to check the identity column in the db.
如果它不起作用,则必须检查数据库中的标识列。
use the key word "identity" to auto increment the id column 使用关键字“identity”自动增加id列
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx 参考: http : //technet.microsoft.com/en-us/library/aa933196(v = sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query 而且你不需要在插入查询中提到“id”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.