2015-12-17 77 views
0

我创建了简单的asp.net c#web页面,显示登录用户的名称,它工作正常,但问题是当我离开该页面打开了一会儿,我刷新或点击它,它给了我一个错误的任何按钮,我不得不回到登录页面,重新登录,使错误走, 此错误消息:异常详细信息:System.Data.SqlClient.SqlException:'='附近的语法不正确

'='附近的语法不正确。说明:执行当前Web请求期间发生未处理的异常 。请 查看堆栈跟踪以获取有关该错误的更多信息,以及源代码中的 。

异常详细信息:System.Data.SqlClient.SqlException:'='附近的语法不正确 。

Source Error: 

Line 22: 
Line 23:   conn.Open(); 
Line 24:   SqlDataReader DR1 = cmd.ExecuteReader(); 
Line 25:   if (DR1.Read()) 

这里是我的代码:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
    SqlCommand cmd = new SqlCommand("select * from usersTable where user_id = "+ Session["userIdSession"], conn); 

    conn.Open(); 
    SqlDataReader DR1 = cmd.ExecuteReader(); 
    if (DR1.Read()) 
    { 
     Label1.Text = DR1.GetValue(1).ToString(); 

    } 
    else 
    { 
     conn.Close(); 
    } 
    } 
+0

'user_id'列的类型是什么? 'Session [“userIdSession”]'的类型和价值是什么?调试您的代码并告诉我们。顺便说一句,你应该总是使用[参数化查询](http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/)。这种字符串连接对于[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)攻击是开放的。并使用'using'语句来处理你的连接,命令和阅读器。 –

+0

[SQL注入警报](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您应该**不**将您的SQL语句连接在一起 - 使用**参数化查询**,以避免SQL注入 –

回答

1

Prooblem与您的代码是,如果Session["userIdSession"]为null,您的查询会是这样: -

select * from usersTable where user_id = 

这显然是一个无效的SQL查询。使用参数化查询并在执行前检查Session["userIdSession"]是否有一些值。

你应该先检查是否Session["userIdSession"]有一些像这样的值: -

if(Session["userIdSession"] != null) 
{ 
    //execute your code 
} 

此外,使用参数化查询,以避免SQL Injection攻击: -

SqlCommand cmd = new SqlCommand("select * from usersTable where user_id = @UserId", conn); 
cmd.Parameters.Add("@UserId",SqlDbType.Int).Value = Convert.ToInt32(Session["userIdSession"]); 

而且,考虑使用using statement自动处理昂贵的对象,如连接。

相关问题