我一直在尝试找出如何使用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");
}
}
答案 0 :(得分:1)
要向
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.
答案 1 :(得分:0)
**非常简单的解决方案
C#文字
query = "insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)"
SQL查询文本
insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)
如果您使用DBNull.Value,则将其在列中保存空字符串