C#各种扩展名文件存入sql server数据库及读取到本地文件

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介: sql server表结构如下: create table DataTable(Id int identity(1,1) not null primary key,FileName nvarchar(100) not null,FilePath nvarchar(200) not null,Data varbinary(MAX) ) 主要方法: using Syst

sql server表结构如下:

create table DataTable
(
Id int identity(1,1) not null primary key,
FileName nvarchar(100) not null,
FilePath nvarchar(200) not null,
Data varbinary(MAX) 
)

主要方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Drawing;

namespace DataAccess
{
    public class PubFunction
    {
        /// <summary>
        /// 把文件存入数据库
        /// </summary>
        /// <param name="filePaths">文件路径(含文件名)</param>
        /// <returns>存入是否成功</returns>
        public static bool StoreFiles(string[] filePaths)
        {
            try
            {
                for (int i = 0; i < filePaths.Length; i++)
                {
                    string filePath = filePaths[i];
                    string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

                    using (SqlConnection connection = new SqlConnection(PubVariant.ConnectionString))
                    {
                        connection.Open();
                        FileStream pFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        byte[] bytes = new byte[pFileStream.Length];
                        pFileStream.Read(bytes, 0, (int)pFileStream.Length);
                        string strSql = "insert into DataTable(FileName,FilePath,Data) values(@FileName,@FilePath,@Data)";
                        using (SqlCommand cmd = new SqlCommand(strSql, connection))
                        {
                            cmd.Parameters.Add("@FileName", SqlDbType.Text);
                            cmd.Parameters.Add("@FilePath", SqlDbType.Text);
                            cmd.Parameters.Add("@Data", SqlDbType.Binary);
                            cmd.Parameters["@FileName"].Value = fileName;
                            cmd.Parameters["@FilePath"].Value = filePath;
                            cmd.Parameters["@Data"].Value = bytes;
                            cmd.ExecuteNonQuery();
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }            
        }

        /// <summary>
        /// 将数据库中数据写入文件
        /// </summary>
        /// <param name="fileName">用于查找数据的文件名</param>
        /// <param name="destFilePath">目标文件路径(含文件名)</param>
        /// <returns>写入是否成功</returns>
        public static bool WriteFromDBtoFile(string fileName, string destFilePath)
        {
            FileStream pFileStream = null;
            try
            {
                using (SqlConnection connection = new SqlConnection(PubVariant.ConnectionString))
                {
                    connection.Open();
                    string strSql0 = "select Data from DataTable where FileName = '{0}'";
                    string strSql1 = String.Format(strSql0, fileName);
                    SqlCommand cmd = new SqlCommand(strSql1, connection);
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();

                    byte[] bytes = (byte[])dr[0];
                    pFileStream = new FileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    pFileStream.Write(bytes, 0, bytes.Length);
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                if (pFileStream != null)
                {
                    pFileStream.Close();
                }
            }
        }

        public static DataTable GetDataFromSql(string strSql)
        {
            using (SqlConnection connection = new SqlConnection(PubVariant.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, connection))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        using (DataSet ds = new DataSet())
                        {
                            da.Fill(ds);
                            DataTable dt = ds.Tables[0];
                            return dt;
                        }
                    }
                }
            }
        }
    }
}

具体实现:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Data.SqlClient;

namespace DataAccess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_MouseClick(object sender, MouseEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            ofd.InitialDirectory = "F:\\";
            ofd.Filter = "All files(*.*)|*.*";
            ofd.Title = "选择文件";
            ofd.ShowDialog();

            PubVariant.filePaths = ofd.FileNames;

            listBox1.DataSource = PubVariant.filePaths;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if(PubFunction.StoreFiles(PubVariant.filePaths))
            {
                MessageBox.Show("Succeed!");
            }
        }

        private void textBox2_MouseClick(object sender, MouseEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "All files(*.*)|*.*";
            sfd.Title = "保存文件";
            sfd.InitialDirectory = "F:\\";
            sfd.FileName = comboBox1.Text;
            sfd.ShowDialog();

            textBox2.Text = sfd.FileName;
            PubVariant.saveFilePath = sfd.FileName;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string fileName = comboBox1.Text;
            if(PubFunction.WriteFromDBtoFile(fileName,PubVariant.saveFilePath))
            {
                MessageBox.Show("Succeed!");
            }
        }

        private void comboBox1_MouseClick(object sender, MouseEventArgs e)
        {
            string strSql = "select FileName from DataTable";
            DataTable dt = PubFunction.GetDataFromSql(strSql);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                comboBox1.Items.Add(dt.Rows[i][0].ToString());
            }
        }

    }
}

全局变量:

public class PubVariant
    {
        public static string[] filePaths;
        public static string saveFilePath;
        public static string connectionString = "server=eagle;database=Test;user id = sa;password=123456";

        public static string ConnectionString
        {
            get { return connectionString; }
            set { connectionString = value; }
        }
    }

实现效果如图:


相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
7天前
|
SQL 人工智能 算法
【SQL server】玩转SQL server数据库:第二章 关系数据库
【SQL server】玩转SQL server数据库:第二章 关系数据库
45 10
|
1月前
|
SQL 数据库 数据安全/隐私保护
Sql Server数据库Sa密码如何修改
Sql Server数据库Sa密码如何修改
|
2月前
|
SQL 算法 数据库
【数据库SQL server】关系数据库标准语言SQL之数据查询
【数据库SQL server】关系数据库标准语言SQL之数据查询
95 0
|
2月前
|
SQL 算法 数据库
【数据库SQL server】关系数据库标准语言SQL之视图
【数据库SQL server】关系数据库标准语言SQL之视图
76 0
|
2月前
|
SQL 人工智能 算法
【数据库SQL server】传统运算符与专门运算符
【数据库SQL server】传统运算符与专门运算符
68 0
|
28天前
|
SQL 数据库
sql server中创建数据库和表的语法
sql server中创建数据库和表的语法
17 1
|
1月前
|
SQL 安全 数据库
SQLServer 实现数据库表复制到另一个数据库_kaic
SQLServer 实现数据库表复制到另一个数据库_kaic
|
7天前
|
SQL 算法 数据库
【SQL server】玩转SQL server数据库:第三章 关系数据库标准语言SQL(二)数据查询
【SQL server】玩转SQL server数据库:第三章 关系数据库标准语言SQL(二)数据查询
62 6
|
7天前
|
SQL 存储 数据挖掘
数据库数据恢复—RAID5上层Sql Server数据库数据恢复案例
服务器数据恢复环境: 一台安装windows server操作系统的服务器。一组由8块硬盘组建的RAID5,划分LUN供这台服务器使用。 在windows服务器内装有SqlServer数据库。存储空间LUN划分了两个逻辑分区。 服务器故障&初检: 由于未知原因,Sql Server数据库文件丢失,丢失数据涉及到3个库,表的数量有3000左右。数据库文件丢失原因还没有查清楚,也不能确定数据存储位置。 数据库文件丢失后服务器仍处于开机状态,所幸没有大量数据写入。 将raid5中所有磁盘编号后取出,经过硬件工程师检测,没有发现明显的硬件故障。以只读方式将所有磁盘进行扇区级的全盘镜像,镜像完成后将所
数据库数据恢复—RAID5上层Sql Server数据库数据恢复案例
|
28天前
|
SQL Oracle 关系型数据库
干货!sqlserver数据库所有知识点总结整理,含代码(挺全的)
干货!sqlserver数据库所有知识点总结整理,含代码(挺全的)
11 0