公共静态类中的非静态成员线程安全吗?
你能帮我检查一下这个功能吗?是线程安全还是不使用。我试图了解公共静态类到底是如何工作的。
该函数将用于通过用户名从数据库获取访问者的userId。可能会发生如此多的并发调用。这也是最好的性能方式和 SQL 注入安全。
ASP.net 4.0 - C# - MSSQL 2008 R2 - IIS 7.5
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class csGetUserId
{
public static string srCommandText = "select UserId from tblUsersProfile where userName=@userName";
public static string ReturnUserId (string srUserName)
{
string srUserId = "0";
using (SqlConnection connection = new SqlConnection(DbConnection.srConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand(srCommandText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@userName", srUserName);
SqlDataReader dsReader = null;
connection.Open();
dsReader = cmd.ExecuteReader();
if (dsReader.HasRows)
{
while (dsReader.Read())
{
srUserId=dsReader["UserId"].ToString();
}
}
else
{
}
}
catch
{
srUserId="-1";
}
}
return srUserId;
}
}
Can you check this function for me. Is it thread safe or not to be used. I am trying to understand how exactly public static classes are working.
This function will be used to get userId of visitor from database by username. So many concurrent call may happen. Also would this be the best performance way and sql injection secure.
ASP.net 4.0 - C# - MSSQL 2008 R2 - IIS 7.5
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class csGetUserId
{
public static string srCommandText = "select UserId from tblUsersProfile where userName=@userName";
public static string ReturnUserId (string srUserName)
{
string srUserId = "0";
using (SqlConnection connection = new SqlConnection(DbConnection.srConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand(srCommandText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@userName", srUserName);
SqlDataReader dsReader = null;
connection.Open();
dsReader = cmd.ExecuteReader();
if (dsReader.HasRows)
{
while (dsReader.Read())
{
srUserId=dsReader["UserId"].ToString();
}
}
else
{
}
}
catch
{
srUserId="-1";
}
}
return srUserId;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设数据库支持多个连接并且您将 srCommandText 更改为只读,则此方法是线程安全的。
将 srCommandText 设置为只读也可以使其安全地防止 SQL 注入。
Assuming that the database supports multiple connections and that you change srCommandText to be readonly then this method is thread safe.
Making srCommandText read-only will also make it safe against SQL injections.