MySQL将文件保存到数据库

时间:2011-05-12 00:52:54

标签: c# mysql

我很难将文件保存到MySQL数据库。

我设法使用此代码将图像保存到数据库

SqlConnection con = new SqlConnection(Properties.Settings.Default.NorthWestConnectionString);
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");

da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
FileStream fs = new FileStream(@"C:\Users\Ruan\Downloads\Gone Fishing.BMP", FileMode.OpenOrCreate, FileAccess.Read);

byte[] MyData = new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));

fs.Close();

da.Fill(ds, "MyImages");

DataRow myRow;
myRow = ds.Tables["MyImages"].NewRow();

myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");

txtboxPassword.Text = MyData.ToString();
con.Close();

但事实是,这增加了一条新线。我只想将图像/ doc添加到现有行。 (最好是文件)

我通常使用此代码更新数据库中的字段。

SqlConnection conn = new SqlConnection();
conn.ConnectionString = Properties.Settings.Default.Studentsdb1ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
String SQL = String.Format("UPDATE Students SET First_Name = '{0}' , Last_Name = '{1}', Birth_Date = '{2}' WHERE Student_Nr = '{3}'", txtName.Text, txtSurname.Text, Convert.ToDateTime(dateTimePicker1.Text).ToString("d"), SelectedStudentNr);


cmd.CommandText = SQL;

cmd.Connection = conn;

object result = null;
ConnectionState previousConnectionState = conn.State;
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
result = cmd.ExecuteScalar();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}


finally
{
if (previousConnectionState == ConnectionState.Closed)
{
conn.Close();
}

所以现在我似乎无法存储文件?我错过了某个地方。

你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

你应该使用SqlParameter type并将它们传递给你的SqlCommand,不仅适用于图像,还适用于任何类型(它更安全,并以“自然”方式进行)。