In programming, we often encounter the problem of "saving files to a database," which is no longer a difficult problem, but may be a little difficult for some of the friends who just started programming. In fact, the method is very simple, but probably because these friends just started programming soon, temporarily did not find a way.
Here's a brief introduction to using C # to accomplish this task.
First, I'll introduce you to save the file to the database. Save the file to the database, in effect, after converting the file into a binary stream, save the binary stream to the corresponding field in the database. The data type for this field in SQL Server is image, which is the OLE object in Access.
Save files to SQL Server database
FileInfo fi=new FileInfo (fileName);
FileStream Fs=fi. OpenRead ();
Byte[] Bytes=new Byte[fs. Length];
Fs. Read (Bytes,0,convert.toint32 (FS). Length));
SqlCommand cm=new SqlCommand ();
Cm. CONNECTION=CN;
Cm.commandtype=commandtype.text;
if (CN. State==0) cn. Open ();
cm.commandtext= "INSERT INTO" +tablename+ "(" +fieldname+ ") VALUES (@file)";
SqlParameter spfile=new SqlParameter ("@file", sqldbtype.image);
Spfile.value=bytes;
Cm. Parameters.Add (SpFile);
Cm. ExecuteNonQuery ()
Save a file in an Access database
FileInfo fi=new FileInfo (fileName);
FileStream Fs=fi. OpenRead ();
Byte[] Bytes=new Byte[fs. Length];
Fs. Read (Bytes,0,convert.toint32 (FS). Length));
OleDbCommand cm=new OleDbCommand ();
Cm. CONNECTION=CN;
Cm.commandtype=commandtype.text;
if (CN. State==0) cn. Open ();
cm.commandtext= "INSERT INTO" +tablename+ "(" +fieldname+ ") VALUES (@file)";
OleDbParameter spfile=new OleDbParameter ("@file", oledbtype.binary);
Spfile.value=bytes;
Cm. Parameters.Add (SpFile);
Cm. ExecuteNonQuery ()
FileName in code is the full name of the file, TableName is the name of the table to be manipulated, FieldName is the name of the field where you want to save the file.
The two pieces of code are actually the same, but the database of the operation is different and the objects used are different.
Then, talking about reading the file from the database, only read from SQL Server.
SqlDataReader Dr=null;
SqlConnection objcn=new SqlConnection ();
Objcn.connectionstring= "Data source= (local); User Id=sa; Password=;initial Catalog=test ";
SqlCommand cm=new SqlCommand ();
Cm. CONNECTION=CN;
Cm.commandtype=commandtype.text;
cm.commandtext= "Select" +fieldname+ "from" +tablename+ "where id=1";
dr=cm. ExecuteReader ();
Byte[] File=null;
if (Dr. Read ())
{
File= (byte[]) dr[0];
}
FileStream FS;
FileInfo fi=new System.IO.FileInfo (fileName);
Fs=fi. Openwrite ();
Fs. Write (file,0,file.length);
Fs. Close ();
The above code reads the file saved in the database and saves the file specified by filename.
When using the above code, don't forget to add System.Data.SqlClient and System.IO references.