【问题标题】:Question about inserting Users/Members into a database table!关于将用户/成员插入数据库表的问题!
【发布时间】:2011-05-29 05:50:00
【问题描述】:

我的注册表单有一个 CreateUserWizard。我使用了它在创建用户后触发的事件。

然后我获取用户身份和密钥。在最后一行中,我将唯一键发送到类中的一个函数,该函数应该将该键插入用户表(该字段是主键并且是唯一的)。

public partial class Registration : System.Web.UI.Page
{
    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);
        int i =(int) CurrentUser.ProviderUserKey;
        RegisterAdo.InsertUsers(i);
    }
}

下面,我使用传递的值执行查询并将用户插入数据库

class RegisterAdo
{
    public static void InsertUsers(int UsersIDentity)
    {
        string myConnectionString = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
        SqlConnection sqlConnect = new SqlConnection(myConnectionString);
        SqlCommand sqlCommand = new SqlCommand(RegisterAdo.insertCommand(UsersIDentity), sqlConnect);
        try
        {
            sqlConnect.Open();
            sqlCommand.ExecuteNonQuery();
        }
        catch (Exception x)
        {

        }
        finally
        {
            sqlConnect.Close();
        }
    }

public static String insertCommand(int UsersIdentityToinsert)
{
    string insertCommand="INSERT INTO Users(";
    insertCommand += "UserID)";
    insertCommand += "VALUES('";
    insertCommand += UsersIdentityToinsert+"')";

    return insertCommand;
}

我的问题是将UserID 插入表中是否是最好的方法,以及我是否完全正确。我需要 UserID 是唯一的,并且整个命令执行没有失败......(就在创建用户并且整个 UserCreateUser 完成验证用户之后!!!

【问题讨论】:

    标签: asp.net sql ado.net


    【解决方案1】:

    我主要会改变两点:

    1. 不要将您的 SQL 语句连接在一起 - 这为 SQL 注入攻击打开了大门。改用参数化查询——它们都更安全,而且性能更好(因为只需要创建和缓存查询执行计划的一个副本,并且会被一遍又一遍地重用)

    2. SqlConnectionSqlCommand 对象放入using 块中,以便在使用块结束时自动释放/处置它们(并且您可以为自己保存@ 的finally 块987654325@ 也构造了!)。

    所以我的代码看起来像这样

        public static void InsertUsers(int UsersIDentity)
        {
            string myConnectionString = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
    
            string insertStmt =
               "INSERT INTO dbo.Users(UserID) VALUES(@UserID)";
    
            using(SqlConnection _con = new SqlConnection(myConnectionString))
            using(SqlCommand _cmd = new SqlCommand(insertStmt, sqlConnect))
            {
               _cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = UsersIDentity;
    
              try
              {
                  _con.Open();
                  _cmd.ExecuteNonQuery();
                  _con.Close();
              }
              catch (Exception x)
              {
                   // do something if error occurs
              }
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多