2011-05-22 10 views
0

我有下面的代碼添加一個新用戶:在形式錯誤在連接簡單引號數據庫

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.SqlClient; 
using System.Data; 

public class users 
{ 

    public Sqlconnection myconn() 
    { 
     return new ("data source=.; integrated security=true; initial catalog=test;"); 
    } 

    public bool insertuser(username, pass, type) 
    { 
     try { 
      string query="insert into users (username, pass, type) values ('"+username+"', '"+pass+"', '"+type+"'); 
      return true; 
      SqlCommand mycommand = new SqlCommand (query, this.myconn); 
      mycommand.Connection.Open(); 
      mycommand.ExecuteNonQuery(); 
      mycommand.Connection.Close(); 
      return true; 
     } 
     catch { 
      return false; 
     } 
    } 
} 

現在如果用戶調用此方法

users user1 = new users(); 

if(user1.insertuser(txtusername.tex, txtpass.text, cbtype.text)==true) 
{ 
    // BUG IS HERE IF USER WRITE SOMETHING SO.. ANGEL' (WITH THIS ') 
    // MY CODE IS GOING TO HAVE A BUG! 
    // I QUIT THEM IN KEY PRESS BUT WHAT HAPPEND IF USERS MUST TO ADD SOMETHING AS 
    // tic's 
    // what can i do for my code acept all?? and it doesn't have any bug? 
    MessageBox.show("user added"); 
} 

回答

3

有一個以上的問題與您的代碼:

  • 您的代碼示例中的第二行是return true;,這意味着它不會運行任何東西InsertUsers
  • 方法參數沒有類型規定
  • 不保持連接打開,配置連接數據檢索
  • 使用using,以保證即使發生了例外
  • 關閉連接/後處理0
  • 使用參數化查詢。在此查找原因:SQL injection
  • 不捕獲所有異常,SQLEXCEPTION只有在這種情況下

試圖從頭使其:

public static bool InsertUser(string userName, string password, string type) 
{ 
    try 
    { 
     using (var connection = new SqlConnection("data source=.; integrated security=true; initial catalog=test;")) 
     using (var command = connection.CreateCommand()) 
     { 
      command.CommandText = "insert into users (username, pass, type) values (@username, @password, @type)"; 
      command.Parameters.AddWithValue("username", userName); 
      command.Parameters.AddWithValue("password", password); 
      command.Parameters.AddWithValue("type", type); 
      connection.Open(); 
      command.ExecuteNonQuery(); 
     } 
     return true; 
    } 
    catch (SqlException) 
    { 
     return false; 
    } 
} 
+0

@angel - 它爲你工作? – 2011-05-23 16:33:28

3

您已經重新發現SQL注入攻擊。

不要在SQL中包含外部派生的值。

改爲使用參數化查詢。

您已經顯示的代碼無論如何不會編譯(Sqlcommand vs SqlCommand),但是讀取this MSDN page(或者只是搜索參數化查詢或SQL注入的信息)以獲取更多信息。

+0

也就是說第一行讓我竊喜 – 2011-05-22 20:16:57

+0

我寫的代碼在這裏,而不是在Visual Studio LOL – angel 2011-05-22 20:20:46

+0

@angel:這意味着它不是你真正的代碼 - 所以我們不知道這個bug是否也在你的真實代碼中。你爲什麼不剪切和粘貼真正的代碼? – 2011-05-22 20:23:05