【问题标题】:Checking if username is available in database检查用户名是否在数据库中可用
【发布时间】:2021-03-20 18:20:37
【问题描述】:

我正在尝试检查用户名是否已在 C# 数据库中使用,它给了我这个错误

SqlConnection cn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project  sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn); 
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
    dr.Close();
    MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
    dr.Close(); 
}

是的,我是新手

【问题讨论】:

  • 您可能在错误的数据库中。在连接字符串中包含初始目录。请检查表名(LoginTable)
  • 不要连接输入 - 它必须"select * from LoginTable where user_name=@userName"或类似的,并添加一个名为@userName的参数,其来自@987654326 @。或者使用像 Dapper 这样的工具可以让这变得更容易。 “Online_Banking”这个名字在 SQLi 旁边是可怕的,老实说。
  • best example 和有趣的 ;)
  • @nilsK SQLi 和 MITM 是非常不同的东西;这里只有 SQLi 相关
  • @MarcGravell 好的,谢谢。你是绝对正确的。

标签: c# sql database dataset


【解决方案1】:

使用这个:

SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);

然后:

var dr = cmd.ExecuteScalar();
if (dr != null)
{
    //Exists
}
else
{
    //Unique username
}

【讨论】:

  • 不,请不要:请注意SQL injections 或“中间人攻击”。
  • 如上所述,“中间人攻击”是完全不同的东西。我的错。现在不能编辑,太晚了,但会在这里留下提示,因为其余的都很重要。
  • 是的。你说的对。理想情况下,他应该使用 AddWithValue。我实际上只是更喜欢实体框架或 Dapper。
【解决方案2】:

Google请:

由于错误是 SqlException: Invalid object name 'Movie' ,因此 表示尚未创建名为“电影”的表或您所在的数据库 指代尚未创建。查看数据库或表“电影”是否有 创建,打开 SQL Server 对象资源管理器并检查数据库名称 与 appsettings 中的相同。 json

请告诉我们你是在哪一行得到的? 是不是这一行 =>if (dr.Read())

【讨论】:

    【解决方案3】:

    让我们提取检查方法:

    private static bool NameAvailable(string name) {
      //DONE: wrap IDisposable into using
      using (SqlConnection cn = new SqlConnection("Connection String Here")) {
        cn.Open();
    
        //DONE: keep Sql readable
        //DONE: make Sql parametrize
        //DONE: select 1 - we don't want entire record but a fact that record exists 
        string sql = 
          @"select 1
              form LoginTable 
             where user_name = @prm_user_name";
    
        using (var cmd = new SqlCommand(sql, cn)) {
          cmd.Parameters.Add("@prm_user_name", SqlDbType.VarChar).Value = name;
    
          using (var dr = cmd.ExecuteReader()) {
            return !dr.Read(); // Not available if we can read at least one record
          }
        }
      }
    }
    

    那你就可以放

     if (!NameAvailable(textBox1)) {
       // Let's be nice and put keyboard focus on the wrong input
       if (textBox1.CanFocus)
          textBox1.Focus();
    
       MessageBox.Show("Username Already exist please try another ", 
                       "Error", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Error);
     }
        
    

    【讨论】:

      【解决方案4】:

      仅进行一些更改。最好了解错误而不是临时解决方案,因此请先打印您的查询并在 sqlserver 中运行它。在我看来,还可以添加初始目录而不是附加 mdf 文件。

       <connectionStrings>
      
      <add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
      
      </connectionStrings>
      

      也使用连接字符串

      SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
              cn.Open();
              string query = "select * from LoginTable where user_name='" +     textBox1.Text.ToString() + "'";
              SqlCommand cmd = new SqlCommand(query, cn);
              SqlDataReader dr = cmd.ExecuteReader();
      
                  //print query  if error and comment the execute reader section when printing the query to know the error  Respone.Write(query);
                  if (!dr.HasRows)
                  {
                     // ur code to insert InsertItemPosition values
              
                  }
                  else
                  {
                      //show username exist
                  }
                  dr.Close();
      

      【讨论】:

        【解决方案5】:

        试试这个:

        string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = @user_name", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@user_name", TextBox1.Text);
        
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    if (dr.HasRows)
                    {
                        if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
                        {
                            // Exists
                        }
                        else
                        {
                            // Doesn't Exist
                        }
                    }
                }
                con.Close();
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-09
          • 2021-12-15
          • 1970-01-01
          • 1970-01-01
          • 2018-10-03
          • 2015-03-14
          • 1970-01-01
          相关资源
          最近更新 更多