Must declare the scalar variable

2019-08-28 06:33发布

问题:

I am getting this error...

Must declare the scalar variable "@Photo"

My insert code looks something like this...

if (image1.Source != null)
{
   FileStream fs = new FileStream("@Photo", FileMode.Open, FileAccess.Read);
   byte[] imgByteArr = new byte[fs.Length];
   fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
   cmd.Parameters.Add(new SqlParameter("Photo", imgByteArr));
}
else
{
   nonqueryCommand.Parameters.AddWithValue("@Photo", DBNull.Value);
}

SQL Server: column name Photo and data type image

I tried the an example from this website. I amended it a little bit because that website uses one click event handler where as I would like to use two click events handlers. One for browse button and the other for insert data. The following code is in the insert handle

FileStream fs = new FileStream("@Photo", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
nonqueryCommand.Parameters.AddWithValue("@Photo", data);

The above code is giving me an error...

Could not find file 'C:....\bin\Debug\@Photo'.

I think this giving me the error because I am not using open dialog coding the same method.

Thanks in advance if anyone can help me.

Update 1a

This will take little time for me to grasp so I will go away. I will take advisement from the guys who have helped. Thanks

回答1:

nonqueryCommand.Parameters.AddWithValue("@Photo", DBNull.Value);

change to

nonqueryCommand.Parameters.AddWithValue("Photo", DBNull.Value);

And also this

new FileStream("@Photo", FileMode.Open, FileAccess.Read);

is clearly wrong. What's @Photo? You can't directly bind SQL columns to C# code. You need to retrieve the value from the database, store it in some variable and then you can use it. Otherwise this code simply tries to find a file named @Photo, which results in an exception as you can see.



回答2:

You are missing @ with parameter

cmd.Parameters.Add(new SqlParameter("@Photo", imgByteArr));
                               ////^^^^ here