C#中此代码的正确命名约定和标准

时间:2014-01-14 05:43:11

标签: c#

请为此代码提供正确的命名约定和标准。 提前谢谢

    public void updateProjectData(ProjectsEvent message)
    {
        MySqlConnection update_connection = new MySqlConnection("server=localhost;database=my_project;port=3306;uid=root;password=;AutoEnlist=false");

        try
        {
            string sql = "UPDATE  `my_project`.`projekte` SET  `desc` =  '"+message.prj_description+"' WHERE  `projekte`.`ID` ="+message.RecordID+";";
            //sqlQuery2 = "update projekte set desc = '"+ message.prj_description.ToString()+"' where ID = " + message.RecordID + "";

            update_connection.Open();
            MySqlCommand command1 = new MySqlCommand(sql, update_connection);
            command1.ExecuteNonQuery();
            update_connection.Close();

        }
        catch (Exception e)
        {
            throw e;
        }
    }

2 个答案:

答案 0 :(得分:2)

我建议这样的事情:

// In C# I'd rather start the public method with the capital letter "U" 
// unlike it in Java where "updateProjectData" is more popular
public void UpdateProjectData(ProjectsEvent message) {
  // Put "using" when working with IDisposable instances
  // Is long "update_connection" really more readable than "conn" for connection?
  // Another issue: why don't move connection string into special field?
  // Say, "private static String s_ConnectionString"?
  // One you've got it (load from resourses, manualy entered etc.)
  // you can use it everywhere when working with database
  using (MySqlConnection conn = new MySqlConnection("server=localhost;database=my_project;port=3306;uid=root;password=;AutoEnlist=false")) {
    conn.Open();

    // Once again, put "using" on IDisposable instances
    // command1 doesn't look very good: what's "1" here?
    // "command" looks more naturally
    using (MySqlCommand command = conn.CreateCommand()) {
      // Why don't you format your query out?
      command.CommandText = 
        "update `my_project`.`projekte`\n" +
        "   set `desc` = @prm_desc\n" +
        " where `projekte`.`ID` = @prm_projekte_id";

      // Beware SQL injection! Use bind variables
      command.Parameters.AddWithValue("@prm_desc", message.prj_description);
      command.Parameters.AddWithValue("@prm_projekte_id", message.RecordID);

      command.ExecuteNonQuery();
    }
  }
}

// finally: this construction is totally useless: you're catching 
// exception, do nothing and throw unchanged exception again -
// why on earth bother to catch it?
// try {
//   ...
// }
// catch (Exception e) {
//   throw e;
// } 

答案 1 :(得分:1)

您可以使用:

  • update_command - >的connectionString

  • sql - >的SqlString

  • command1 - > updateCommand

您的代码中也存在SQL注入的可能性。

你是说这个吗?