我一直试图弄清楚如何使用null和image值将图像保存到数据库中.对于我的代码,它保存图像,但如果图像丢失,则不保存空值.
public string STDNAME { get; set; }
public string Image { get; set; }
DateTime Date1 = DateTime.Now;
这是我用来保存数据的代码
public string imagepath { get; set; }
public bool Insert(StudentC c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
byte[] imageBT = null;
FileStream fstream = new FileStream(this.Image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBT = br.ReadBytes((int)fstream.Length);
string sql = "INSERT INTO STUDENT (STDNAME,imagepath,Image,Date) VALUES (@STDNAME,@imagepath,@Image,@Date)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@STDNAME", c.STDNAME);
cmd.Parameters.AddWithValue("@imagepath", c.imagepath);
cmd.Parameters.AddWithValue("@Image", imageBT);
cmd.Parameters.AddWithValue("@Date", Date1);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
Console.WriteLine("\nMessage ---\n{0}", ex.Message);
}
finally
{
conn.Close();
}
return isSuccess;
}
此代码用于浏览图像
//browse image
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 2;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox2.Image = Image.FromFile(f.FileName);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.BorderStyle = BorderStyle.Fixed3D;
textBox7.Text = f.SafeFileName.ToString();
string picPath = f.FileName.ToString();
textBox7.Text = picPath;
pictureBox2.ImageLocation = picPath;
}
}
这是为存储提供值的代码
private void button5_Click(object sender, EventArgs e)
{
c.STDNAME = textBox2.Text;
c.Image = textBox7.Text;
c.imagepath = textBox7.Text;
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("Data has been saved");
//Clear();
}
else
{
// label4.Text = "Data Has not been saved";
MessageBox.Show("Data has not been saved");
}
}
最佳答案 要向图像列添加null,请确保指定类型(例如VarBinary),如下例所示.此外,请确保image列接受null.
cmd.Parameters.Add("@Image", SqlDbType.VarBinary).Value = DBNull.Value;
此外,以下方法可能会导致以下例外情况:
cmd.Parameters.AddWithValue("@Image", DBNull.Value);
—例外—
System.Data.SqlClient.SqlException (0x80131904): Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.