2016-11-21 73 views
-1

当我在下面运行我的代码时,发生以下错误。我正在运行用户注册页面,其中包含名字,姓氏,用户名,密码等详细信息。 “ID”是我的主要关键。错误:“在System.Data.dll中发生类型'System.ArgumentException'的异常,但未在用户代码中处理 附加信息:初始化字符串的格式不符合从索引0开始的规范。”在用户代码中未处理SQL异常

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Configuration; 
using System.Data.SqlClient; 
using System.Data; 


namespace WebApplication_Assignment 
{ 
    public partial class User_Registration_WebForm : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     protected void Button_SubmitUserReg_Click(object sender, EventArgs e) 
     { 
      //Response.Write("Your registration is successful"); 

      string sql = "SELECT * from User_Table where User_Name = @username"; 

      using (SqlConnection connection = new SqlConnection("ConnectionString")) 
      using (SqlCommand command = new SqlCommand(sql, connection)) 
{ 
    var userParam = new SqlParameter("username", SqlDbType.VarChar); 
    userParam.Value = TextBox_UserName.Text; 

    command.Parameters.Add(userParam); 

    var results = command.ExecuteReader(); 
} 
+0

为什么你的错误日志代码被注释掉了?让我们看看实际的异常消息,请...另外:不要连接字符串:使用参数 –

+0

我有错误记录代码的错误,所以删除它与代码的其余部分继续前进,这些错误是:错误CS1519:类,结构或接口成员声明中的无效标记'catch',错误CS1002:;预期的错误CS1519:无效的标记'('在类,结构或接口成员声明中,错误CS0116:名称空间不能直接包含成员,如字段或方法 – sullkid16

+0

这里是完整的错误,当我注释掉错误日志代码时,在System.Data.dll中发生类型'System.Data.SqlClient.SqlException'类型的异常,但未在用户代码中处理 附加信息:“Sullivan”附近的语法错误 字符串'后未使用引号') ”。 – sullkid16

回答

0

因为您没有使用参数,所以您的姓氏(姓氏)几乎肯定是“O'Sullivan”请参阅单引号;它导致TSQL语句不正确地形成。

如果连接字符串,会遇到类似问题,并打开自己的SQL注入攻击。始终使用参数。

这里有一个简单的例子:

string sql = "SELECT * from employee where username = @username"; 

using (SqlConnection connection = new SqlConnection("connection string") 
using (SqlCommand command = new SqlCommand(sql, connection)) 
{ 
    var userParam = new SqlParameter("username", SqlDbType.VarChar); 
    userParam.Value = txtUsername.Text; 

    command.Parameters.Add(userParam); 

    var results = command.ExecuteReader(); 
} 

有对SO SQL注入攻击多次提到。这里有一个例子:

Why do we always prefer using parameters in SQL statements?

+0

是的,我使用的是这个姓氏,但删除它,并使用“奥沙利文”,仍然是同样的错误。 – sullkid16

+0

我将如何将它们更改为参数? – sullkid16

+0

SqlDbType.VarChar,该代码的SqlDBType部分有下划线说明它不存在于当前上下文中? – sullkid16

相关问题