[英]C# : how to upload image to a SQL Server database using varbinary(Max)
我一直在嘗試將圖像上傳到我的數據庫,但出現此錯誤:
不允許從數據類型 varchar 到 varbinary(max) 的隱式轉換。 使用 CONVERT function 運行此查詢
這是我的代碼:
con.Open();
cmd = new SqlCommand("SELECT * FROM ImagePosts", con);
ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
int id = ds.Tables[0].Rows.Count + 1;
byte[] buffer = File.ReadAllBytes(file);
SqlCommand cmd2 = new SqlCommand("INSERT INTO Images (Id, Title, Image) VALUES('" + id + "', '" + textBox1.Text + "', '" + "@image" + "')", con);
var binary1 = cmd2.Parameters.Add("@image", SqlDbType.VarBinary, -1);
binary1.Value = buffer;
cmd2.ExecuteNonQuery();
con.Close();
this.Close();
編輯:我的錯,我忘了刪除@image 周圍的括號。
您不需要在 sql 服務器中將 varbinary 數據用單引號括起來。 嘗試這個
SqlCommand cmd2 = new SqlCommand("INSERT INTO Images (Id, Title, Image) VALUES('" + id + "', '" + textBox1.Text + "', @image)", con);
問題是您在應該只是@image 時插入'@image'。 如果您輸入 '',則表示您想將值“@image”插入到字段中。 刪除'',它應該可以工作。 但是,我也建議對 Textbox.Text 執行相同的操作,否則您可以獲得 Sql 注入:
con.Open();
cmd = new SqlCommand("SELECT * FROM ImagePosts", con);
ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
int id = ds.Tables[0].Rows.Count + 1;
byte[] buffer = File.ReadAllBytes(file);
SqlCommand cmd2 = new SqlCommand("INSERT INTO Images (Id, Title, Image) VALUES('" + id + "', @Title, @image)", con);
cmd2.Parameters.Add("@Title", textBox1.Text);
var binary1 = cmd2.Parameters.Add("@image", SqlDbType.VarBinary, -1);
binary1.Value = buffer;
cmd2.ExecuteNonQuery();
con.Close();
this.Close();
你甚至可以用 ID 來做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.