2013-06-05 68 views
0
 MySqlConnection con = new MySqlConnection("host=db4free.net;user=*;password=*;database=*;"); 
    MySqlCommand xcmd = new MySqlCommand("SELECT x FROM members WHERE id='" + Login.idd + "';"); 
     xcmd.Connection = con; 
     xint.Connection = con; 
     DataTable dt = new DataTable(); 
     con.Open(); 
     xcmd.ExecuteNonQuery(); 
     int xx = (int)xcmd.ExecuteScalar(); 
     xcmd.Connection.Close();; 
     xcmd.Dispose(); 
     x = xx; 
     con.Close(); 
     if (x == 2) 
     { 
      button6.BackgroundImage = Properties.Resources.logo; 
     } 

我希望程序從數據庫中讀取X的值,它加入一個變量,然後如果它等於2,顯示標誌...C#DB列值

+0

除了你的字符串連接的SQL注入問題,究竟是什麼問題?你不需要'DataTable'或'ExecuteNoneQuery'行。 – dash

+0

和'xInt.Connection'是一個總括號... – Steve

回答

0

在你的原始代碼中,你有一些你不需要的位;例如,數據表中,XINT命令,爲ExecuteNonQuery(這是做的東西,只有更新/插入/從數據庫中刪除,例如,不返回結果)

using(MySqlConnection con = new MySqlConnection("host=db4free.net;user=*;password=*;database=*;")) 
{ 
    using(MySqlCommand xcmd = new MySqlCommand("SELECT x FROM members WHERE [email protected];")) 
    { 
     xcmd.connection = con; 
     xcmd.Parameters.AddWithValue("@loginid", Login.idd); 
     con.Open(); 
     int x = Convert.ToInt32(xcmd.ExecuteScalar()); 
     //Do something with x 
     if(x == 2) 
     { 
      button6.BackgroundImage = Properties.Resources.logo; 
     } 
    } 
} 

如果你是將要做這種數據訪問的風格,我會建議您的查詢parameterizing,並使用'using'聲明。

第一個將幫助防止SQL注入攻擊,第二個將確保在您離開各個塊的範圍時處理非管理資源。

+0

仍然沒有在按鈕中顯示圖像。 –

+0

如果您在代碼中放置了斷點,它是否會輸入「x == 2」塊?你使用什麼樣的應用程序? Windows窗體,ASP.Net,WPF? – dash

+0

Windows窗體並且沒有 –

0

使用ExecuteScalar ,它更直截了當:

MySqlConnection con = new MySqlConnection("host=db4free.net;user=*;password=*;database=*;"); 
MySqlCommand xcmd = new MySqlCommand("SELECT x FROM members WHERE id='" + Login.idd + "';", con); 

con.Open(); 
var x = (int)xcmd.ExecuteScalar(); 
con.Close(); 
if (x == 2) 
{ 
    button6.BackgroundImage = Properties.Resources.logo; 
} 

進一步,請注意由破折號提供了答案。我通常將這一點加入我的答案中,並且正在處理中,但看到了他的補充。

還有一個關於設置BackgroundImage的註釋 - 您需要使用LayoutSize。以下代碼來自MSDN:

// Specify the layout style of the background image. Tile is the default. 
button1.BackgroundImageLayout = ImageLayout.Center; 

// Make the button the same size as the image. 
button1.Size = button1.BackgroundImage.Size; 

上面的那些設置可能不正確基於您的圖像。

+0

運算符'=='不能應用於類型'object'和'int'的操作數 –

+0

@VlasiuRobert,請參閱我的編輯。我爲'(int)'添加了一個強制類型來允許該語句成功。 –