当前位置:网站首页>C # import CSV into MySQL database
C # import CSV into MySQL database
2022-06-29 07:52:00 【Mzz steed】
private void add to ToolStripMenuItem_Click(object sender, EventArgs e)
{
// string[] sInsert = new string[] { "1", "2" ," normal "," normal "," normal ","123","www","2022-05-23 00:09:00"," On-Site Inspection ","2"};
// insert_Tble(sInsert,2);
//DataTable mytable= new DataTable();
//mytable.Columns.Add("name",Type.GetType("System.String"));
//mytable.Columns.Add("xuehao",Type.GetType("System.String"));
//DataRow myrow = mytable.NewRow();
//myrow["name"]=" Xiao Wang ";
//myrow["xuehao"]="20200101";
//mytable.Rows.Add(myrow);
//mytable.TableName = "test";
DataTable mytable;
mytable=ReadCSV("D:/Test03.csv");
mytable.TableName = "test";
int ct= mytable.Rows.Count;
Console.WriteLine(mytable.Columns[0].ToString());
BulkInsert(mytable);
// AddRec addrecord = new AddRec();
// addrecord.ShowDialog();
}
/// <returns> Returns the number of rows successfully inserted </returns>
public int BulkInsert(DataTable table)
{
if (string.IsNullOrEmpty(table.TableName)) throw new Exception(" Please DataTable Of TableName Attribute with table name ");
if (table.Rows.Count == 0) return 0;
int insertCount = 0;
string tmpPath = Path;
string csv = DataTableToCsv(table);
File.WriteAllText(tmpPath, csv);
//MySqlTransaction tran = null;
//using (MySqlConnection conn = new MySqlConnection(connectionString))
using (MySqlConnection conn_n = conn)
{
MySqlTransaction tran = null;
try
{
conn_n.Open();
tran = conn.BeginTransaction();
MySqlBulkLoader bulk = new MySqlBulkLoader(conn_n)
{
CharacterSet = "UTF8",// Add this character configuration Solve the Chinese garbled code
FieldTerminator = ",",
FieldQuotationCharacter = '"',
EscapeCharacter = '"',
LineTerminator = "\r\n",
FileName = tmpPath,
NumberOfLinesToSkip = 0,
TableName = table.TableName,
};
bulk.Columns.AddRange(table.Columns.Cast<DataColumn>().Select(colum => colum.ColumnName).ToArray());
insertCount = bulk.Load();
tran.Commit();
}
catch (MySqlException ex)
{
// if (tran != null) tran.Rollback();
throw ex;
}
conn_n.Close();
}
//File.Delete(tmpPath);
return insertCount;
}
/// <summary>
/// Read CSV file csv The first column is the field name
/// </summary>
/// <param name="filePath"> File path </param>
public static DataTable ReadCSV(string filePath)
{
try
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
string strLine = null; // Record one line of records read at a time
string[] arrayLine = null; // Record the contents of each field in each line of record
// Separator
//string[] separators = { "," };
// Judge , If it's the first time , Create header , Whether to read the first line
bool isFirst = true;
// Read line by line CSV file
while ((strLine = sr.ReadLine()) != null)
{
strLine = strLine.Trim(); // Remove the leading and trailing spaces
arrayLine = strLine.Split(','); // Delimited string , Returns an array of
int dtColumns = arrayLine.Length; // Number of columns
if (isFirst) // Create header
{
for (int i = 0; i < dtColumns; i++)
{
dt.Columns.Add(arrayLine[i]); // Name of each column
}
isFirst = false;
}
else // Table content
{
DataRow dr = dt.NewRow();// Create a new line
for (int j = 0; j < dtColumns; j++)
{
dr[j] = arrayLine[j].Replace("\"\"", "\""); // Replace the two English double quotation marks with 1 Double quotes
}
dt.Rows.Add(dr);// Add a row
}
}
sr.Close();
fs.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
/// <returns> Return standard CSV</returns>
private static string DataTableToCsv(DataTable table)
{
// Comma with half angle ( namely ,) As separator , If the column is empty, its existence should also be expressed .
// If half width commas exist in the column contents ( namely ,) Use half angle quotation marks ( namely "") Include the value of the field .
// If there are half quotes in the column contents ( namely ") Should be replaced by half width double quotation marks ("") escape , With half angle quotation marks ( namely "") Include the value of the field .
StringBuilder sb = new StringBuilder();
DataColumn colum;
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
colum = table.Columns[i];
if (i != 0) sb.Append(",");
if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
{
sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
}
else sb.Append(row[colum].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
边栏推荐
- Up and down transitions in polymorphism
- Appium environment setup
- 1032 Sharing
- 道闸控制器通讯协议
- 数组知识点小结
- Vulnhub's dc9 target
- Kyushu cloud helps Inner Mongolia's "counting from the east to the west" project to drive the smart new ecology of the surveying and mapping industry
- 反思 - 完美主义
- 反思 - 中小公司项目管理思维 - 先将产品做出来,先将功能做出来
- Appium自动化测试基础 — ADB常用命令(三)
猜你喜欢

【域渗透提权】CVE-2020-1472 NetLogon 权限提升漏洞

施努卡:3d视觉检测方案 3d视觉检测应用行业

Reasons why the ext.dic file configured in ES does not take effect

编译原理王者之路

Vulnhub's dc6 target

Listen to textarea input through Keyup to change button style

What you should know about databases

Common MySQL errors and solutions summarized painstakingly (II)

pycharm的虚拟环境如何共享到jupyter-lab

Handle series - install spotbugs and use them quickly
随机推荐
声波通讯 - 流式数据处理 - 窗口对齐
时间操作 - 时间格式转换
358. K distance interval rearrange string sorting
施努卡:什么是视觉定位系统 视觉定位系统的工作原理
ES中配置ext.dic文件不生效的原因
蓝桥杯——13届第二批试题解析
【工控老马】基于PLC的花样喷泉设计原理详解
Prompt during packaging: property 'sqlsessionfactory' or 'sqlsessiontemplate'‘
【域渗透提权】CVE-2020-1472 NetLogon 权限提升漏洞
VMware vcenter/ESXI系列漏洞总结
面试官:为什么数据库连接很消耗资源,资源都消耗在哪里?
Appium environment setup
719. find the distance of the number pair with the smallest K (two points)
Vulnhub's DC8 target
【深度之眼吴恩达机器学习作业班第四期】Regularization正则化总结
The table cannot be vacuumed because the cursor is open for a long time
Kyushu cloud helps Inner Mongolia's "counting from the east to the west" project to drive the smart new ecology of the surveying and mapping industry
Kingbasees coping with transaction rollback caused by too fast growth of table age
How to permanently set Mysql to utf8 encoding?
Swin Transformer理论讲解