2014-02-10 6 views
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; 
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 

я искал ошибку в Интернете, но я не получил должного ответа.

+0

пользователь является зарезервированным словом SQL – Matt

+6

[ГОСПОДА, дезинфицировать ВАШИ ДАННЫЕ ВХОДЫ] (http://xkcd.com/327 /) – Codeman

+0

В отличие от сайтов форума, мы не используем «Спасибо», «Любая благодарность» или подписи на [so]. См. «[Должны ли« Привет »,« спасибо », теги и приветствия удалены из сообщений?] (Http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed-from-posts). –

ответ

3

User является запасным словом. Итак, окружайте User в вашем SQL с помощью [..].

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)); 

Наконец, вы должны приложить SqlConnection и SqlCommand объекты в Using блоке так ресурсы автоматически уничтожаются в конце.

1

Это

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

Для этого:

string checkuser = "select count(*) from [user] where username='" + TextBoxun.Text + "'"; 
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()); 
      } 
     } 
    } 
} 
+1

Можете ли вы объяснить * почему * ваш код решает проблему? Пожалуйста, см. [ответ]. – brasofilo

Смежные вопросы