繁体   English   中英

c#DB列值

[英]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 -您需要使用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;

根据您的图像,以上那些设置可能不正确。

在原始代码中,您不需要一些内容。 例如,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM