SQL Server数据库不会更新新信息

时间:2017-02-01 15:56:23

标签: sql-server sql-insert

我不明白。这段代码应该可行,但必须有一些我做错了。

谁能看到我做错了什么?

public static int InsUpDel(string str)
{
    if (!(conn.State == ConnectionState.Open)) 
        conn.Open(); //open connection if closed

    int numRows = 0; //counter that checks number of rows affected in the db

    try
    {
        SqlCommand cmd = new SqlCommand(str, conn);
        numRows = cmd.ExecuteNonQuery();
        cmd = null;
    }
    catch (SqlException ex)
    {
        string errorMsg = ex.Message; //more code can be put here               
    }

    if (conn.State == ConnectionState.Open) 
        conn.Close();

    return numRows;
}

这是后续行动:

Lambda<String>

谢谢。

1 个答案:

答案 0 :(得分:2)

附注:

  1. 始终使用查询参数,绝不使用字符串连接。有趣的是Bobby Tables
  2. 不要使用静电,你需要的地方不多。
  3. 不要共享数据库连接,创建它们并根据需要销毁它们。
  4. 不要将密码存储为纯文本!
  5. 不要捕捉您不打算处理的异常。记录它们并重新抛出(使用throw;)或根本不捕获。最后一个将帮助您弄清楚为什么&#34;它不起作用&#34;
  6. 更新了代码

    public void UpdateUser() {
      var userModel = new UserModel {
        Username = tbNewUSER.Text.Trim(),
        Password = tbNewPass.Text.Trim(),
        Role = "USER"
      };
    
      var result = UpdateUser(userModel);
    }
    
    
    public int UpdateUser(UserModel user)
    {
        const string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values (@userName, @password, @role)";
        using(var conn = new SqlConnection("your connection string here, hint best to get it from the app.config"))
        using(var command = new SqlCommand(str, conn))
        {
          command.Parameters.Add(new SqlParameter("@userName", SqlDbType.VarChar, 255) {Value = user.UserName});
          command.Parameters.Add(new SqlParameter("@password", SqlDbType.VarChar, 255) {Value = user.Password});
          command.Parameters.Add(new SqlParameter("@role", SqlDbType.VarChar, 255) {Value = user.Role});
          conn.Open();
          return cmd.ExecuteNonQuery();
        }
    }
    

    <强> UserModel.cs

    public class UserModel {
      public string UserName {get;set;}
      public string Password {get;set;}
      public string Role {get;set;}
    }