【问题标题】:How to return specific row from database that include image path如何从包含图像路径的数据库中返回特定行
【发布时间】:2021-11-30 00:58:46
【问题描述】:

我在下面编写的代码正确地返回了一个图像,该图像的路径存储在数据库中。

[HttpGet("{id}")]
public IActionResult RetrieveFile(int id)
{
    string pathImage = "";

    DataTable table = new DataTable();
    string query = @"select image from mydb.courses where id=@id";

    string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
    MySqlDataReader myReader;

    using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();

        using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myCommand.Parameters.AddWithValue("@id", id);
            pathImage = (string)myCommand.ExecuteScalar();
            mycon.Close();
        }
    }

    var path = @$"{pathImage}";
    var fs = new FileStream(path, FileMode.Open);
    return File(fs, "image/jpeg");
}

另外,我想从数据库中返回idpricename,并将其发送给客户端。

我应该对上述代码进行哪些更改才能向我发送我想要的内容?

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-web-api


    【解决方案1】:

    您不能使用 ExecuteScalar,但您需要调用 ExecuteReader 来取回 MySqlDataReader,然后从读取器字段中获取单个输入。当然,您应该更改查询以获取必填字段

    string query = @"select id,price,name,image from mydb.courses where id=@id";
    string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
    using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myCommand.Parameters.AddWithValue("@id", id);
            // Then you use the reader to get the single field values
            using(MySqlDataReader myReader = myCommand.ExecuteReader())
            {
                // Always check if the where clause produces records to read
                if(myReader.Read())
                {
                    // I have assumed the datatype for the fields. Change GetXXXX if different
                    pathImage = myReader.GetString("image");
                    id = myReader.GetInt32("id");
                    price = myReader.GetDecimal("price");
                    name = myReader.GetString("name");
                }
            }
        }
    }
    

    请注意,在 using 语句中声明连接时,您无需关闭连接。另外最好不要使用 AddWithValue 尽管在整数的情况下它的问题是不相关的,而且 MySql 似乎比其他数据库更有弹性

    【讨论】:

    • 嗨@Steve,感谢您的回答。现在,如何将 pathImage、id、price 和 name 值返回给客户端?
    • 它们现在是单独的变量。我建议您创建一个具有支持这 4 个值的属性的类。创建此类的一个实例并使用数据读取器返回的值设置属性。现在您只需将类实例返回给调用代码
    猜你喜欢
    • 1970-01-01
    • 2012-02-24
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多