簡體   English   中英

SQL Csv w/ > C# 中的 255 列的有效方法?

[英]Efficient Way to SQL Csv w/ > 255 Columns in C#?

我有以下我非常喜歡的 OleDb 方法,因為我最終可以通過針對 csv 的 SQL 查詢。

問題是 OleDb 只能讀取 < 256 列,而我擁有的不止這些。

以這樣的列大小有效查詢 C# 中的 csv 表的替代方法是什么?

我想避免將整個 csv 放入數據表中以供以后的 LINQ 使用。

            DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
            {
                string header = isFirstRowHeader ? "Yes" : "No";

                string pathOnly = Path.GetDirectoryName(path);
                string fileName = Path.GetFileName(path);

                string sql = @"SELECT * FROM [" + fileName + "]";

                using (OleDbConnection connection = new OleDbConnection(
                          @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
                          ";Extended Properties=\"Text;HDR=" + header + "\""))
                using (OleDbCommand command = new OleDbCommand(sql, connection))
                using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                {
                    DataTable dataTable = new DataTable
                    {
                        Locale = CultureInfo.CurrentCulture
                    };
                    adapter.Fill(dataTable);
                    return dataTable;
                }
            }

更新:嘗試在以下腳本的建議中添加評論以使用 ACE 驅動程序,但以下 OleDb 連接字符串仍然只能獲得 255 列。 仍在尋找一種方法來實現這一點。

using (OleDbConnection connection = new OleDbConnection(
                      "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + pathOnly +"; Extended Properties =\"Text; HDR = Yes; FORMAT = Delimited\""))

像這樣的東西怎么樣?:

        static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
        {
            DataTable dataTable = null;

            using (var inStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var sr = new StreamReader(inStream))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    var fields = line.Split(',');

                    if (dataTable == null) // create datatable based on header row
                    {
                        dataTable = new DataTable();
                        foreach (var field in fields)
                            dataTable.Columns.Add(new DataColumn(field));
                        continue; // don't add header row to rows collection
                    }

                    dataTable.Rows.Add(fields);
                }
            }

            return dataTable;
        }

如果您的第一行不是 header,則您必須想出一種不同的方法來命名列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM