使用存储在数据库中的图像(图像路径)

时间:2013-02-16 16:19:11

标签: c# winforms

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

        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();",但我不知道要使用什么语法。

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

试试这个:

        while (reader.Read())
        {
            string path = reader.GetString(0);
            button11.Image = Image.FromFile(path);                    
        }

答案 2 :(得分: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);
        }
    } 
相关问题