MySQL将文件保存到数据库

MySQL将文件保存到数据库

问题描述:

我努力将文件保存到我的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(); 
} 

那么现在我似乎无法存储文件?我在某处失去了某些东西。

你能帮我一下吗?

+1

虽然大多数较新版本的数据库都允许将二进制文件数据存储在数据库中,但这是一个糟糕的主意。我会说从数据库中来回传输大量数据会影响性能。我的建议是保存它在数据库中的服务器上的位置的路径,而不是.. – 2011-05-12 02:28:01

+1

MySql?代码似乎在MS SQL – Anuraj 2011-05-12 04:39:32

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

+0

Okyyy,我得到,所以它不只是图像...谢谢彼得。 – mrbunyrabit 2011-05-12 23:11:49

+0

哦,是的,你能告诉我我在哪里标记这个问题解决? – mrbunyrabit 2011-05-12 23:12:32