2014-01-14 111 views
0

請爲此代碼提供適當的命名約定和標準。 由於事先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; 
     } 
    } 
+4

擺脫那個try/catch塊。它沒有任何用處,實際上,它會擾亂你的堆棧跟蹤。你還應該把'SqlConnection'和'SqlCommand'放到''using''塊中。 –

+2

這屬於http://codereview.stackexchange.com/。 –

+0

好的約翰和什麼應該是對象的格式? – Ash

回答

0

您可以使用:

  • update_command - >的connectionString

  • SQL - >的SqlString

  • 命令1 - >更新命令

也有是在你的代碼的SQL注入的可能性。

這是你的意思嗎?

1

我建議這樣的事情:

// 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; 
// }