【问题标题】:How to File Upload csv to SQL database on intranet VB.NET site如何将 csv 文件上传到 Intranet VB.NET 站点上的 SQL 数据库
【发布时间】:2012-09-18 15:38:06
【问题描述】:

我在将 CSV 文件上传到我的 SQL 数据库时遇到问题。我正在尝试通过 Intranet 站点上的文件上传技术来实现这一点。 Intranet 站点是为我和另一个用户提供文件上传这些 CSV 的能力(以防我们中的一个人外出)。

我用过以下的;

    Dim errorList As String = String.Empty
    Dim returnValue As Integer = 0
    Dim SQLCon As New SqlClient.SqlConnection
    Dim SQLCmd As New SqlClient.SqlCommand
    Dim ErrString As String

    Dim countRecs As Integer = 0
    Dim batchid As Integer = GetNextBatchNumber("PartsImport")

    Using tf As New TextFieldParser(fileandpath)
        tf.TextFieldType = FileIO.FieldType.Delimited
        tf.SetDelimiters(",")


        SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
        SQLCon.Open()
        SQLCmd.CommandType = CommandType.Text
        SQLCmd.Connection = SQLCon

        Dim recAdded As String = Now.ToString
        Dim row As String()
        While Not tf.EndOfData

            Try
                row = tf.ReadFields()
                Dim x As Integer = 0
                If countRecs <> 0 Then
                    Try
                      SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
                      + " (ID,PartName,PartID,Price,ShipAddress) " _
                      + " values ('" + row(0) + "','" + row(1) + "','" _
                      + row(2) + "','" + row(3) + "','" + row(4) + "')"
                        SQLCmd.ExecuteNonQuery()

                    Catch ex As Exception
                        ErrString = "Error while Creating Batch Record..." & ex.Message
                    End Try
                End If

            Catch ex As MalformedLineException
                errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
            End Try
            countRecs = countRecs + 1
        End While

        SQLCon.Close()
        SQLCon.Dispose()
        SQLCmd.Dispose()

当我点击表格按钮上传时,它给了我一条成功消息,但是当我查看实际表格时,它仍然是空白的。

有什么想法吗?欣赏它

谢谢 戴夫

【问题讨论】:

  • 在您看不到的地方更可能存在一些错误。您可能想要运行 SQL Profiler 来查看实际访问数据库的 SQL。此外,您的 CSV 导入可能存在问题。我最近使用了这个 CSV 库并喜欢它:github.com/JoshClose/CsvHelper。它也可以在 NuGet 上使用。
  • 另外,显示更多代码,并确保格式化。
  • 如果您使用相同的连接发出选择语句会发生什么:SQLCmd.CommandText = "SELECT * [Base].[PartsImport]";
  • 我执行了 SELECT 语句,但仍然对 SQL 数据库没有任何区别或添加。我添加了更多我的代码。希望这能让您更清楚地了解问题所在。

标签: asp.net sql-server vb.net csv intranet


【解决方案1】:
private void UploaddataFromCsv()
        {
            SqlConnection con = new SqlConnection(@"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
            string filepath = "C:\\params.csv";
            StreamReader sr = new StreamReader(filepath);
            string line = sr.ReadLine();
            string[] value = line.Split(',');
            DataTable dt = new DataTable();
            DataRow row;
            foreach (string dc in value)
            {
                dt.Columns.Add(new DataColumn(dc));
            }

            while ( !sr.EndOfStream )
            {
                value = sr.ReadLine().Split(',');
                if(value.Length == dt.Columns.Count)
                {
                    row = dt.NewRow();
                    row.ItemArray = value;
                    dt.Rows.Add(row);
                }
            }
            SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
            bc.DestinationTableName = "[Base].[PartsImport]";
            bc.BatchSize = dt.Rows.Count;
            con.Open();
            bc.WriteToServer(dt);
            bc.Close();
            con.Close();
        }

【讨论】:

  • 很好的例子,但我建议在你的答案中添加一些 cmets 来描述你在做什么。
【解决方案2】:

尝试捕获 SqlException 并查看您的请求是否存在格式问题。如果 ID 上有标识列,则不应从 CSV 显式设置它,因为这可能会导致潜在的重复项提交到您的数据库。另外,我怀疑您的类型中有一些类型不匹配,因为您在看似数字列的地方加上引号。我建议您考虑将查询中的字符串连接替换为使用参数来避免不正确的引号转义问题(即,如果您的 PartName 为“O'Reily's auto parts”会发生什么?)这样的事情可能会奏效。请注意,我在 LINQ 世界中待了这么久,这里可能会出现一些语法错误。

SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
        SQLCon.Open()
        SQLCmd.CommandType = CommandType.Text  'Setup Command Type
        SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
                      + " (PartName,PartID,Price,ShipAddress) " _
                      + " values (@PartName, @PartID, @Price, @ShipAddress)'"
        Dim partNameParam = New SqlParameter("@PartName", SqlDbType.VarChar)
        Dim partIdParam = New SqlParameter("@PartID", SqlDbType.Int)
        Dim partPriceParam = New SqlParameter("@Price", SqlDbType.Money)
        Dim partAddressParam = New SqlParameter("@ShipAddress", SqlDbType.VarChar)
        SQLCmd.Parameters.AddRange(  {partNameParam, partIdPAram, partPriceParam, partAddressParam})
        SQLCmd.Connection = SQLCon

        Dim recAdded As String = Now.ToString()
        Dim row As String()
        While Not tf.EndOfData

            Try
                row = tf.ReadFields()
                Dim x As Integer = 0
                If countRecs <> 0 Then
                    Try
                       partNameParam.Value = row[1]
                       partIdParam.Value = row[2]
                       partPriceParam.Value = row[3]
                       partAddressParam.Value = row[4]

                       SQLCmd.ExecuteNonQuery()

                    Catch ex As Exception
                        ErrString = "Error while Creating Batch Record..." & ex.Message
                    End Try
                End If

            Catch ex As MalformedLineException
                errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
            End Try
            countRecs = countRecs + 1
        End While

        SQLCon.Close() 'TODO: Change this to a Using clause
        SQLCon.Dispose() 
        SQLCmd.Dispose() 'TODO: Change this to a Using clause

话虽如此,如果您要插入大量项目,批量复制示例是一个更好的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2011-01-19
    • 2022-08-06
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多