繁体   English   中英

如何将图像插入数据库?

[英]How do I insert an image into a database?

public void InsertAnImage(Guid i)
{
    StringBuilder sb = new StringBuilder();

    sb.Append("");

    Stream stream = FileUpload1.FileContent;
    StreamReader reader = new StreamReader(stream);

    string myConnectionString = AllQuestionsPresented.connectionString;
    using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString))
    {
        // sample query with parameters to insert into db
        string sqlQuery = "INSERT INTO [UserProfile] (UserID, Picture) Values (@userId, @picture)";
        // conn is your db connection
        SqlCommand command = new SqlCommand(sqlQuery, conn);
        // creating parameters
        SqlParameter paramId = new SqlParameter("@userId", SqlDbType.Int, 4);
        paramId.Value = 45;
        // you picture parameter, and assigning its the value
        SqlParameter paramPicture = new SqlParameter("@picture", SqlDbType.Binary, myImage.Length);// red line here
        paramPicture.Value = myImage;// red line here
        // adding params to command
        command.Parameters.Add(paramId);
        command.Parameters.Add(paramPicture);
        // then execute your command
        command.ExecuteNonQuery();
    }
}

如何将流阅读器而不是 Filestream 阅读器放入数据库?

这是另一篇文章:

使用 ASP.NET 2.0 和 ASP.NET 3.5 从数据库中保存和检索图像

但是,普遍的共识是最好将图像存储在文件系统中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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