0

我希望此按钮的图像使用存储在数据库中的图像(图像路径)...

        private void button15_Click(object sender, EventArgs e)
        {
            string a = button11.Text;
            string connString = "Server=Localhost;Database=test;Uid=*****;password=*****;";
            MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand command = conn.CreateCommand();
            command.CommandText = ("Select link from testtable where ID=" + a);

            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                //button11.Image = ex.ToString();
            }

            MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                button11.Image = reader["path"].ToString();                    
            }
        } 

我认为错误在于,"reader["path"].ToString();"但我不知道要使用什么语法。

4

3 回答 3

0

如果您在path列中存储了磁盘上图像文件的路径,则应加载该图像:

    string path = (string)reader["path"];
    button11.Image = Image.FromFile(path);

旁注:切勿将值直接从用户输入传递到数据库查询。它容易受到 sql 注入攻击。改用参数:

command.CommandText = "Select link from testtable where ID=@id";
command.Parameters.AddWithValue("@id", int.Parse(a));
于 2013-02-16T16:30:55.330 回答
0

试试这个:

        while (reader.Read())
        {
            string path = reader.GetString(0);
            button11.Image = Image.FromFile(path);                    
        }
于 2013-02-16T16:34:22.077 回答
0

试试这个:(写权回答框,可能有错别字!)

    private void button15_Click(object sender, EventArgs e)
    {
        string a = button11.Text;
        string imagePath;
        string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
        using(MySqlConnection conn = new MySqlConnection(connString))
        using(MySqlCommand command = conn.CreateCommand())
        {
            command.CommandText = "Select link from testtable where ID=@id";
            command.Parameters.AddWithValue("@id", int.Parse(a));

            try
            {
                conn.Open();
                imagePath= (string)command.ExecuteScalar();
            }
            catch (Exception ex)
            {
            //button11.Image = ex.ToString();
            }

            button11.Image = Image.FromFile(imagePath);
        }
    } 
于 2013-02-16T16:35:27.790 回答