[英]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;
}
I want the program to read the value of X from the database, add it in a variable and then if it is equal to 2 to show the logo... 我希望程序从数据库中读取X的值,将其添加到变量中,然后将其等于2以显示徽标...
Use ExecuteScalar
, it's much more straight forward: 使用
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;
}
further, please take note to the answer provided by dash . 此外,请注意dash提供的答案。 I generally add that to my answers, and was in the process, but saw his addition.
我通常将其添加到我的答案中,并且正在处理中,但是看到了他的添加。
And a note about setting a BackgroundImage
-you need to work with the Layout
and Size
. 还有关于设置
BackgroundImage
-您需要使用Layout
和Size
。 The following code is from MSDN: 以下代码来自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;
those settings above may not be right based on your image. 根据您的图像,以上那些设置可能不正确。
In your original code, you have some bits you don't need; 在原始代码中,您不需要一些内容。 for example, the DataTable, the xint command, and the ExecuteNonQuery (which is for doing stuff which only updates/inserts/deletes from the database, for example, and doesn't return results)
例如,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;
}
}
}
If you are going to be doing this style of data access, I would recommend parameterizing your query, and using the ' using ' statement. 如果您打算采用这种数据访问方式,则建议您对查询进行参数化 ,并使用' using '语句。
The first will help prevent SQL Injection attacks, while the second will ensure non-managed resources are disposed of when you leave the scope of the various blocks. 第一个将帮助防止SQL Injection攻击,第二个将确保在离开各个块的作用域时处置非托管资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.