我在将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()
当我点击表单按钮上传时,它会给我一条成功消息,但是当我查看实际表格时,它仍然是空白的。
有什么想法吗?欣赏它
由于 戴夫
答案 0 :(得分: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();
}