我正在努力将文件保存到我的 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/