简体   繁体   English

MySQL将文件保存到数据库

[英]MySQL Save File to Database

I'm struggling to save a file to my MySQL database. 我正在努力将文件保存到我的MySQL数据库中。

I managed to save a image to the database with this code 我设法用此代码将图像保存到数据库

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

But the thing is that this adds a new line. 但事实是,这增加了一条新线。 I simply want to add an image/doc to an existing row. 我只想将图像/文档添加到现有行。 (Preferably a document) (最好是文件)

I usually use this code to update fields in my db. 我通常使用此代码来更新数据库中的字段。

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

So now I can't seem to store a file? 所以现在我似乎无法存储文件了? I am missing something somewhere. 我在某处缺少某物。

Could you please help me out? 你能帮我吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM