前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用Microsoft.VisualBasic中TextFieldParser解析器把CSV格式倒入数据库

利用Microsoft.VisualBasic中TextFieldParser解析器把CSV格式倒入数据库

作者头像
用户1161731
发布2018-01-11 12:59:54
7050
发布2018-01-11 12:59:54
举报
文章被收录于专栏:木宛城主

写了个Demo,利用Microsoft.VisualBasic这个程序集中的TextFieldParser解析器解析CSV格式的文件,然后将解析的数据插入到相关表,这样的好处是不用去用令人头疼的ODBC去操作CSV格式文件,如之前是这样去操作:

利用ODBC去操作

代码语言:javascript
复制
string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + this.dirCSV.Trim() + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";
                    string sql_select;
                    OdbcConnection conn;
                    conn = new OdbcConnection(strConnString.Trim());
                    conn.Open();
                    OdbcCommand commandRowCount = new OdbcCommand("SELECT COUNT(*) FROM [" + this.FileNevCSV.Trim() + "]", conn);
                    this.rowCount = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
                    sql_select = "select * from [" + this.FileNevCSV.Trim() + "]";
                    OdbcCommand commandSourceData = new OdbcCommand(sql_select, conn);
                    OdbcDataReader dataReader = commandSourceData.ExecuteReader();
                    DataTable dt;
                    dt = dataReader.GetSchemaTable();

利用TextFieldParser操作

代码语言:javascript
复制
namespace ImportCSV
{
    class Program
    {
        //连接字符串
        private static readonly string connStr = @"Data Source=BEAR\EYESSQLSERVER;Initial Catalog=Test;Integrated Security=True";
        //表明,最好做成是客配置,如Winform程序下拉框
        private static string tableName = "Customer";
        /// <summary>
        /// 执行查询,返回DataTable数据源
        /// </summary>
        /// <param name="connStr"></param>
        /// <param name="cmdText"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        static DataTable ExecuteDataTable(string connStr,string cmdText,params SqlParameter[] parameters)
        {
            using (SqlConnection conn=new SqlConnection(connStr))
            {
                using (SqlCommand cmd=conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    cmd.Parameters.AddRange(parameters);
                    using (SqlDataAdapter adapter=new SqlDataAdapter(cmd))
                    {
                        DataTable dataTable=new DataTable();
                        adapter.Fill(dataTable);
                        return dataTable;
                    }
                }
            }
        }
        /// <summary>
        /// 得到主键列
        /// </summary>
        /// <returns></returns>
        static List<string> GetKeyWords()
        {
            //SQL Server 系统试图得到主键列
            string sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME=@TABLE_NAME";
            DataTable dt=ExecuteDataTable(connStr, sql, new SqlParameter("TABLE_NAME", tableName));
            List<string> listKeyWords=new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                string keyWord = Convert.ToString(row["COLUMN_NAME"]);
                listKeyWords.Add(keyWord);
            }
            return listKeyWords;
        }
        /// <summary>
        /// 得到指定表所有的列
        /// </summary>
        /// <returns></returns>
        static List<string> GetAllColumns()
        {
            //系统视图得到所有列
            string sql = "select * from  INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TABLE_NAME";
            DataTable dt = ExecuteDataTable(connStr, sql, new SqlParameter("TABLE_NAME", tableName));
            List<string> listCols = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                string columnName = Convert.ToString(row["COLUMN_NAME"]);
                listCols.Add(columnName);
            }
            return listCols;
        }
        /// <summary>
        /// 得到初主键外所有列
        /// </summary>
        /// <returns></returns>
        static List<string> GetAllColumnsWithoutKeyWords()
        {

            List<string> listAllColumns = GetAllColumns();
            List<string> listKeyWords= GetKeyWords();
            return listAllColumns.Except(listKeyWords).ToList();
        }
        /// <summary>
        /// 得到除Identity(标识)外所有列
        /// </summary>
        /// <returns></returns>
        static List<string> GetAllColumnsWithoutIdentity()
        {
            //得到Identity标志列
            string sql = @"select COLUMN_NAME
                                    from INFORMATION_SCHEMA.COLUMNS
                                    where TABLE_SCHEMA = 'dbo'
                                    and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                                    and TABLE_NAME=@TABLE_NAME";
            DataTable dt = ExecuteDataTable(connStr, sql, new SqlParameter("TABLE_NAME", tableName));
            List<string> listColumnsWithoutIdentity = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                listColumnsWithoutIdentity.Add(Convert.ToString(row["COLUMN_NAME"]));
            }
            List<string> listAllColumns = GetAllColumns();
            //从所有列中排除
            return listAllColumns.Except(listColumnsWithoutIdentity).ToList();
        }

   

        static void Main(string[] args)
        {
            
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = connection.CreateCommand())
                {
                    //得到所有列除Identity标志列
                    string[] columnsWithoutIdentity = GetAllColumnsWithoutIdentity().ToArray();
                    //SQL参数
                    string[] columnsParameters = (from c in columnsWithoutIdentity select "@" + c).ToArray();

                    StringBuilder sb=new StringBuilder();
                    //拼接Insert SQL语句
                    sb.AppendLine("insert into " + tableName + "(" + string.Join(",", columnsWithoutIdentity) +
                                  ") output inserted.id values(" + string.Join(",",columnsParameters)+ ")");
                    cmd.CommandText = sb.ToString();
                    //从路径得到csv的文件,可以做成打开框
                    using (var myCsvFile = new TextFieldParser(@"C:\Users\eyeswang\Desktop\xxxx.csv",Encoding.Default))
                    {
                        myCsvFile.TextFieldType = FieldType.Delimited;
                        myCsvFile.SetDelimiters(",");//设置解析器分割符
                        connection.Open();
                        //循环,一行一行读
                        while (!myCsvFile.EndOfData)
                        {
                            string[] fieldArray;
                            try
                            {
                                //读取一行
                                fieldArray = myCsvFile.ReadFields();
                                for (int i = 0; i < fieldArray.Count(); i++)
                                {
                                   //给参数赋值,如果是NULL,则DBNULL.Value插入相关列
                                    cmd.Parameters.Add("@" + columnsWithoutIdentity[i], fieldArray[i].ToUpper() == "NULL" ? (object)DBNull.Value : fieldArray[i]);
                                }
                               //执行完毕后记得Parameters Clear
                                cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                            }
                            catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex)
                            {

                                continue;

                            }

                        }
                    }

                }
            }
            Console.WriteLine("OK");
            Console.ReadKey();

        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013-06-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 利用ODBC去操作
  • 利用TextFieldParser操作
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档