我读取了一个逗号分隔值文本文件并将其解析为 C# 列出四个字符串。一个字符串的字符串日期格式为:
"20090501 00:00:00.308"
另一个字符串包含类似于 10.00001 的 float 据类型。
我想使用来自 How to bulk insert into MySQL using C# 的以下 C# 代码
var bl = new MySqlBulkLoader(connection);
bl.TableName = "mytable";
bl.FieldTerminator = ",";
bl.LineTerminator = "\r\n";
bl.FileName = "myfileformytable.csv";
bl.NumberOfLinesToSkip = 1;
var inserted = bl.Load();
Debug.Print(inserted + " rows inserted.");
问题是我想将 CSV 字符串数据类型转换为正确的 MySQL 数据类型 DECIMAL 和 DATETIME。 我可以使用上面的源代码示例并仍然使用它进行即时转换吗?如果是这样,那怎么办。如果没有,我还有吗 一次使用 SQL 插入一个并在每个单独的插入上进行转换?
最佳答案
问题是存储在 CSV 文件中的格式是“dd/MM/yyyy”,但在 MySQL 中它的格式是“yyyy/MM/dd”,所以我相信这就是现在的问题所在。 你在这里找到解决方案 https://social.msdn.microsoft.com/Forums/vstudio/en-US/1a280038-4c0f-4fb1-950d-1529269a1c73/issue-with-datetime-format-in-bulkloader-program?forum=csharpgeneral
这是我新的生成 csv 文件的方法:
public static void CreateCSVfile(DataTable dt, string strFilePath)
{
#region Export Grid to CSV
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
Type _datetype = typeof(DateTime);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(
dt.Columns[i].DataType == _datetype
? ((DateTime)dr[i]).ToString(CultureInfo.InvariantCulture.DateTimeFormat)
: dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
关于c# - C# MYSQL MySqlBulkLoader 可以动态转换数据类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316627/