[英]Using the SQL bulk copy in C# and deleting the string headers
下面的代码是我用于将txt文件中存储的数据插入sql的代码:
public void extract_data()
{
openFileDialog1.ShowDialog();
DataTable dt = new DataTable();
StreamReader sr = new StreamReader(openFileDialog1.FileName);
string input;
dt.Columns.Add(new DataColumn("Counter", typeof(string)));
dt.Columns.Add(new DataColumn("Machine", typeof(string)));
dt.Columns.Add(new DataColumn("Employee_Number", typeof(string)));
dt.Columns.Add(new DataColumn("In_Out", typeof(string)));
dt.Columns.Add(new DataColumn("DateTime", typeof(string)));
while ((input = sr.ReadLine()) != null)
{
string[] s = input.Split(new char[] { '\t' });
DataRow dr = dt.NewRow();
dr["Counter"] = s[0];
dr["Machine"] = s[1];
dr["Employee_Number"] = s[2];
dr["In_Out"] = s[5];
dr["DateTime"] = s[6];
dt.Rows.Add(dr);
}
using (SqlBulkCopy sqbc = new SqlBulkCopy(@"Data Source=DBASE;Network Library=DBMSSOCN;Initial Catalog=DB;User ID=sa;Password=123"))
{
sqbc.BatchSize = 10000;
sqbc.BulkCopyTimeout = 10000;
sqbc.ColumnMappings.Add("Counter", "Counter");
sqbc.ColumnMappings.Add("Machine", "Machine");
sqbc.ColumnMappings.Add("Employee_Number", "Employee_Number");
sqbc.ColumnMappings.Add("In_Out", "In_Out");
sqbc.ColumnMappings.Add("DateTime", "DateTime");
sqbc.DestinationTableName = "tblExtract";
sqbc.WriteToServer(dt);
}
}
如您所见,由于txtfile中的标头(我们可以将其分类为字符串),因此我无法将列DateTime转换为sqlserver中的datetime。 批量复制将返回错误,因为它无法在datetime格式列中插入字符串,因此我被迫将DateTime列声明为string以适应这种情况。 但我想更改它。 我想将其声明为datetime。 在执行sqlbulk复制时如何忽略标题文本? 我想跳过标题文本,仅复制数据
尝试这个 :
string format = "MM/dd/yyyy hh:mm:ss.fff";
DateTime d =DteTime.ParseExact(s[6],format,System.Globalization.CultureInfo.InvariantCulture);
dr["DateTime"]=d;
根据需要更改格式,例如“ MM / dd / yyyy”或“ MM / dd / yyyy hh:mm”等
您可以将值转换为DateTime:
dr["DateTime"] = Convert.ToDateTime(s[6]);
这会起作用,但是如果您遇到的不是日期时间,可能会很危险。 如果您遇到这种情况,则最有可能要使用DateTime.TryParse进行操作。
如果您总是要跳过单个标题行,只需将现有的while()包装在if()内,即可读取该行而不对其进行处理。
if ((input = sr.ReadLine()) != null)
{
// already read line #1 (i.e. header line),
// now start processing data, if any lines exist
while ((input = sr.ReadLine()) != null)
{
...
}
}
一般注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.