2011-05-12 202 views
0

我努力將文件保存到我的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

回答

1

您應該使用SqlParameter type並將它們傳遞給您的SqlCommand,不僅適用於任何形式的圖像(它更安全並且以「自然」方式進行)。

+0

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

+0

哦,是的,你能告訴我我在哪裏標記這個問題解決? – mrbunyrabit 2011-05-12 23:12:32