[英]c# DB Column Values
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以顯示徽標...
使用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;
}
此外,請注意dash提供的答案。 我通常將其添加到我的答案中,並且正在處理中,但是看到了他的添加。
還有關於設置BackgroundImage
-您需要使用Layout
和Size
。 以下代碼來自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;
根據您的圖像,以上那些設置可能不正確。
在原始代碼中,您不需要一些內容。 例如,DataTable,xint命令和ExecuteNonQuery(用於執行僅從數據庫進行更新/插入/刪除操作,而不返回結果的操作)
using(MySqlConnection con = new MySqlConnection("host=db4free.net;user=*;password=*;database=*;"))
{
using(MySqlCommand xcmd = new MySqlCommand("SELECT x FROM members WHERE id=@loginid;"))
{
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;
}
}
}
如果您打算采用這種數據訪問方式,則建議您對查詢進行參數化 ,並使用' using '語句。
第一個將幫助防止SQL Injection攻擊,第二個將確保在離開各個塊的作用域時處置非托管資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.