我真的很困惑。我有3个名为id,title,images的表。我想做的是将图像存储在db中。但是我不能。我在这一行得到例外
int id = Convert.ToInt32(cmd.ExecuteScalar());
连接状态似乎是开放的。我还需要检查什么?
SqlConnection connection = null;
try
{
Byte[] imgByte = null;
if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
{
HttpPostedFile File = FileUpload1.PostedFile;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
connection = new SqlConnection("server=.\\sqlexpress;database=Northwind;UID=sa;Password=1234");
connection.Open();
string sql = "INSERT INTO imgtable (title,images) VALUES(@theTitle, @theImage) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@theTitle", txtTitle.Text);
cmd.Parameters.AddWithValue("@theImage", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
答案 0 :(得分:0)
我的水晶球告诉我你得到一个关于无效SQL语法的错误。那是因为你不能通过在一行上写它们来执行两个语句。
在INSERT
和SELECT
之间添加分号:
string sql = "INSERT INTO imgtable (title,images) VALUES(@theTitle, @theImage); SELECT @@IDENTITY";
答案 1 :(得分:0)
如果查看MSDN文档SQLCommand ExecuteScalar,他们会给出一个完整的示例:
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
Juste将int id = Convert.ToInt32(cmd.ExecuteScalar());
替换为int id = (Int32)cmd.ExecuteScalar();
。
同样编辑你的SQL语句:" INSERT INTO imgtable(title,images)VALUES(@theTitle,@ theImage); SELECT CAST(scope_identity()AS int)&#34 ;;