如何在asp.net C#的下一行编写SQL查询 [英] How to write SQL Query in next line in asp.net C#
问题描述
嗨朋友们,
如何在下一行写下插入查询。
我的数据库中有很多字段。 />
这是我的代码...它显示错误
sqlcommand cmd = new sqlcommand(INSERT into UserInfo VALUES('+ TxtUserName.Text +','+ TxtPassword.Text +','+ TxtFirstName.Text +','+ TxtLastName.Text +'),con);
请帮助谢谢
Hi friends,
How to write Insert query in next line.
I have lot of fields in my database.
This is my code...it shows error
sqlcommand cmd = new sqlcommand("INSERT into UserInfo VALUES('" + TxtUserName.Text + "','" + TxtPassword.Text + "','" + TxtFirstName.Text + "','" + TxtLastName.Text + "')",con);
Please help thanks
推荐答案
您将获得的第一个错误是 sqlcommand
并且该错误将是
The first error you will get is on sqlcommand
and that error will be
找不到类型或命名空间名称'sqlcommand'(您是否错过了使用指令或程序集引用?)
The type or namespace name 'sqlcommand' could not be found (are you missing a using directive or an assembly reference?)"
那是因为它应该是 SqlCommand
- C#是区分大小写的语言。有一个讨论为什么可能在这个链接上 [ ^ ]
接下来,您将(最终)遇到问题,因为您正在连接文本框内容以构建您的sql字符串。您应该使用参数化查询 - 此链接提供一些原因 [ ^ ]
下一个可能的问题是由您的评论提示的
That's because it should be SqlCommand
- C# is a case-sensitive language. There's a discussion on why that might be on this link[^]
Next you will (eventually) get problems because you are concatenating textbox contents to build your sql string. You should use Parameterized Queries - this link gives some reasons why[^]
Next possible issue is prompted by your comment
我的数据库中有很多字段。 />
I have lot of fields in my database.
如果您的表 UserInfo
的列数多于您尝试插入的四个值,那么您必须让SQL Server知道您提供的列(参考 [ ^ ] )。当您提供的值与列定义的顺序不同时,情况也是如此。例如。在你的情况下(我已经猜到了列名)
If your table UserInfo
has more columns than the four values you are trying to insert, then you must let SQL Server know which columns you are providing (reference[^]). The same is true when you provide values that are not in the same order that the columns were defined. E.g. in your case (I have guessed at the column names)
INSERT into UserInfo (UserName, Password, FirstName, LastName) VALUES(...
根据您提供的信息,此代码应该适用于您
This code should work for you given the information you've provided
string sql = "INSERT into UserInfo (UserName, Password, FirstName, LastName) VALUES(@UserName,@Password,@FirstName,@LastName)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@UserName", TxtUserName.Text);
cmd.Parameters.AddWithValue("@Password", TxtPassword.Text);
cmd.Parameters.AddWithValue("@FirstName", TxtFirstName.Text);
cmd.Parameters.AddWithValue("@LastName", TxtLastName.Text);
尝试以下。
try following.
string cmdtxt="";
cmdtxt = cmdtxt + "INSERT into UserInfo VALUES('" + TxtUserName.Text ;
cmdtxt = cmdtxt + "','" + TxtPassword.Text + "','" + TxtFirstName.Text + "','" + TxtLastName.Text ;
sqlcommand cmd = new sqlcommand(cmdtxt,con);
这篇关于如何在asp.net C#的下一行编写SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!