Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试将数据插入数据库时出错_C# - Fatal编程技术网

C# 尝试将数据插入数据库时出错

C# 尝试将数据插入数据库时出错,c#,C#,我试图将数据插入数据库,但出现了一些错误 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient;//provide all the classes of the sql using System.Configuratio

我试图将数据插入数据库,但出现了一些错误

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;//provide all the classes of the sql
using System.Configuration;
public partial class registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
         SqlConnection conn=new SqlConnection(ConfigurationManager.ConnectionStrings["registrationConnectionString"].ConnectionString);
         conn.Open();
        string checkuser = "select count(*) from user where username='" + TextBoxun.Text + "'";
         SqlCommand com = new SqlCommand(checkuser,conn);
         int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
         if (temp == 1)
         {
             Response.Write("user already exists");
         }

         conn.Close();
        }

    }

    protected void Button1_Click1(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["registrationConnectionString"].ConnectionString);
            conn.Open();
            string insertquery = " insert into user (username,email,password,country) values (@uname,@email,@password,@country) ";
            SqlCommand com = new SqlCommand(insertquery, conn);
            com.Parameters.AddWithValue("@uname", TextBoxun.Text);
            com.Parameters.AddWithValue("@email", TextBoxemail.Text);
            com.Parameters.AddWithValue("@password", TextBoxpw.Text);
            com.Parameters.AddWithValue("@country", DropDownListcn.SelectedItem.ToString());
            com.ExecuteNonQuery();
            Response.Redirect("manager.aspx");
            Response.Write("registration is successful");
            conn.Close();
        }
        catch(Exception ex)
        {
            Response.Write("error:" + ex.ToString());
        }

    }
} 
我得到的错误是

Server Error in '/' Application.
Incorrect syntax near the keyword 'user'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'user'.

Source Error:


Line 17:         string checkuser = "select count(*) from user where username='" + TextBoxun.Text + "'";
Line 18:          SqlCommand com = new SqlCommand(checkuser,conn);
Line 19:          int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Line 20:          if (temp == 1)
Line 21:          {


Source File: c:\Users\Admin\Documents\Visual Studio 2012\WebSites\learn1\registration.aspx.cs    Line: 19

Stack Trace:


[SqlException (0x80131904): Incorrect syntax near the keyword 'user'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753346
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295154
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
   System.Data.SqlClient.SqlDataReader.get_MetaData() +90
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1325
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteScalar() +149
   registration.Page_Load(Object sender, EventArgs e) in c:\Users\Admin\Documents\Visual Studio 2012\WebSites\learn1\registration.aspx.cs:19
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929 

我在互联网上搜索了这个错误,但没有得到正确的答案。

User
是一个保留字。因此,在SQL中用
[…]
用户
包围起来,就像这样

string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'";
string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'";
还可以参数化
TextBoxun.Text
,以避免SQL注入攻击。i、 像下面这样

string checkuser = "select count(*) from [user] where username= @UserName ";, connection))
  // Add new SqlParameter to the command.
  //
 com .Parameters.Add(new SqlParameter("@UserName", TextBoxun.Text));

最后,应该使用块将
SqlConnection
SqlCommand
对象包含在
中,以便在最后自动释放资源。

用户
是保留字。因此,在SQL中用
[…]
用户
包围起来,就像这样

string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'";
string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'";
还可以参数化
TextBoxun.Text
,以避免SQL注入攻击。i、 像下面这样

string checkuser = "select count(*) from [user] where username= @UserName ";, connection))
  // Add new SqlParameter to the command.
  //
 com .Parameters.Add(new SqlParameter("@UserName", TextBoxun.Text));
最后,您应该使用
块将
SqlConnection
SqlCommand
对象包含在
中,以便在最后自动释放资源。

string checkuser = "select count(*) from user where username='" + TextBoxun.Text + "'";
为此:

这个

为此:


用户是SQL中的保留字(旁注-永远不要将用户输入的文本放入您的SQL语句中。您正在为自己设置SQL注入攻击)与论坛网站不同,我们不使用“感谢”或“感谢任何帮助”或签名。请参阅“.Bobby Tables肯定是Stackoverflow评论中发布最多的链接。user是SQL中的保留字(旁注-永远不要将用户输入的文本放入您的SQL语句中。您正在为自己设置SQL注入攻击)。与论坛网站不同,我们不使用“谢谢”或“感谢任何帮助”“,或在上签名。请参阅“.Bobby Tables肯定是Stackoverflow评论中发布最多的链接。您能解释一下为什么您的代码解决了这个问题吗?请参阅。您能解释一下为什么您的代码解决了这个问题吗?请参阅。