c# - MySQL 将文件保存到数据库

标签 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();

但问题是这增加了一个新行。我只想将图像/文档添加到现有行。 (最好有文档)

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

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();
}

所以现在我似乎无法存储文件?我在某处遗漏了一些东西。

你能帮我一下吗?

最佳答案

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

关于c# - MySQL 将文件保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5972215/

相关文章:

c# - 记录哈希表属性

c# - 我应该手动编码 ADO.Net 数据库访问吗?

mysql - 获取每小时发生的事件数

java - 更新以 mysql blob 格式保存的图像

php - 如何将数组的所有键插入数据库

c# - C# 中的 HTML 元素属性

C# 异步方法根据第一个完成的任务执行

c# - 秒表多任务ElapsedMilliseconds计算

mysql - Sql触发器的查询

MySQL 不正确的整数值(编码)