使用C#将二进制文件保存到数据库中

使用C#将二进制文件保存到数据库中
public void FileSaveToSQL()
{
         string strConnection = @"Provider=SQLOLEDB;Data Source=机器名\SQLEXPRESS;Initial Catalog=master;Integrated Security=SSPI;";

        OleDbConnection DBConn;
        OleDbCommand DBCommand;

         try
        {
                DBConn = new OleDbConnection(strConnection);
                DBConn.Open();
                DBCommand = DBConn.CreateCommand();
                DBCommand.CommandText = "insert TestTable (A, E) VALUES (99, ?)";

                FileStream fs = new FileStream( @"C:\tempIn\temp0.txt", FileMode.Open, FileAccess.Read);
                Byte[] b = new Byte[fs.Length];
                fs.Read(b, 0, b.Length);
                fs.Close();

                OleDbParameter prm = new OleDbParameter( "@E", OleDbType.VarBinary, b.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, b);
                DBCommand.Parameters.Add(prm);

                 if (DBCommand.ExecuteNonQuery() == 1)
                {
                        Console.WriteLine( "OK");
                }
                 else
                {
                        Console.WriteLine( "Fail");
                }

                DBConn.Close();
        }
         catch (Exception e)
        {
                System.Console.WriteLine( "Err");
        }
}
 
使用C#将数据库中的二进制文件保存到本地
public void FileReadFromSQL()
{
         string strConnection = @"Provider=SQLOLEDB;Data Source=机器名\SQLEXPRESS;Initial Catalog=master;Integrated Security=SSPI;";

        OleDbConnection DBConn;
        OleDbCommand DBCommand;
        OleDbDataReader DBReader;

         try
        {
                DBConn = new OleDbConnection(strConnection);
                DBConn.Open();
                DBCommand = DBConn.CreateCommand();
                DBCommand.CommandText = @"SELECT E FROM TestTable WHERE A = 99";
                DBReader = DBCommand.ExecuteReader();

                 while (DBReader.Read())
                {
                         byte[] File = ( byte[])DBReader[0];

                        FileStream fs = new FileStream( @"C:\tempOut\temp0.txt", FileMode.CreateNew);
                        BinaryWriter bw = new BinaryWriter(fs);
                        bw.Write(File, 0, File.Length);
                        bw.Close();
                        fs.Close();
                }
                DBConn.Close();
        }
         catch (Exception e)
        {
                System.Console.WriteLine( "Err");
        }
}

你可能感兴趣的:(数据库,二进制,C#,职场,休闲)