尝试将数据插入数据库时​​出错

时间:2014-02-10 18:39:18

标签: 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.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 

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

3 个答案:

答案 0 :(得分:3)

User是一个保留字。因此,请将SQL User[..]包围在一起。

string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'";

同时参数化TextBoxun.Text以避免SQL注入攻击。即如下。

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

最后,您应该将SqlConnectionSqlCommand对象括在Using块中,以便最后自动处理资源。

答案 1 :(得分:1)

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

对此:

string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'";

答案 2 :(得分:0)

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;

namespace Registerpage

{

    public partial class Registerwebpage : System.Web.UI.Page

    {
        protected void Page_Load(object sender, EventArgs e)

        {
            if (IsPostBack)

            {

                SqlConnection conn = new           SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
                conn.Open();
                string checkuser = "select count(*) from [Table1] where Username='" + TextBoxUN.Text + "'";
                SqlCommand com = new SqlCommand(checkuser, conn);
                Int32 count = Convert.ToInt32(com.ExecuteScalar().ToString());


                if (count == 1)
                {
                    Response.Write("user already exists");
                }

                conn.Close();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
                conn.Open();
                string insertquery = " insert into [Table1] (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", TextBoxPass.Text);
                com.Parameters.AddWithValue("@country", DropDownListCountry.SelectedItem.ToString());
                com.ExecuteNonQuery();
                Response.Redirect("RegisterDatabase.aspx");
                Response.Write("registration is successful");
                conn.Close();
            }
            catch (Exception ex)
            {
                Response.Write("error:" + ex.ToString());
            }
        }
    }
}