mrbunyrabit
mrbunyrabit

Reputation: 3

MySQL Save File to Database

I'm struggling to save a file to my MySQL database.

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?

Upvotes: 0

Views: 3661

Answers (1)

pabdulin
pabdulin

Reputation: 35219

You should use SqlParameter type and pass them to your SqlCommand, not only for images but for any kind (it's more secure and goes in "natural" way).

Upvotes: 1

Related Questions