当前位置:网站首页>C#导入csv到mysql数据库中
C#导入csv到mysql数据库中
2022-06-29 06:41:00 【MZZ骏马】
private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
{
// string[] sInsert = new string[] { "1", "2" ,"正常","正常","正常","123","www","2022-05-23 00:09:00","巡检","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"]="小王";
//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>
public int BulkInsert(DataTable table)
{
if (string.IsNullOrEmpty(table.TableName)) throw new Exception("请给DataTable的TableName属性附上表名称");
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",//添加此字符配置 解决中文乱码
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>
/// 读取CSV文件 csv第一列为字段名
/// </summary>
/// <param name="filePath">文件路径</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; //记录每次读取的一行记录
string[] arrayLine = null; //记录每行记录中的各字段内容
//分隔符
//string[] separators = { "," };
//判断,若是第一次,建立表头,是否读取第一行
bool isFirst = true;
//逐行读取CSV文件
while ((strLine = sr.ReadLine()) != null)
{
strLine = strLine.Trim(); //去除头尾空格
arrayLine = strLine.Split(','); //分隔字符串,返回数组
int dtColumns = arrayLine.Length; //列的个数
if (isFirst) //建立表头
{
for (int i = 0; i < dtColumns; i++)
{
dt.Columns.Add(arrayLine[i]); //每一列名称
}
isFirst = false;
}
else //表内容
{
DataRow dr = dt.NewRow();//新建一行
for (int j = 0; j < dtColumns; j++)
{
dr[j] = arrayLine[j].Replace("\"\"", "\""); //将两个英文双引号替换回1个双引号
}
dt.Rows.Add(dr);//添加一行
}
}
sr.Close();
fs.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
/// <returns>返回标准的CSV</returns>
private static string DataTableToCsv(DataTable table)
{
//以半角逗号(即,)作分隔符,列为空也要表达其存在。
//列内容如存在半角逗号(即,)则用半角引号(即"")将该字段值包含起来。
//列内容如存在半角引号(即")则应替换成半角双引号("")转义,并用半角引号(即"")将该字段值包含起来。
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();
}
边栏推荐
- pycharm的虚拟环境如何共享到jupyter-lab
- Unexpected exception ... code: Badrequest when downloading Xilinx 2018.2
- Postman pre request
- code::blocks代码格式化快捷键
- KingbaseES应对表年龄增长过快导致事务回卷
- [industrial control old horse] detailed design of PLC six way responder system
- Vibration signal generation and processing based on MATLAB Doppler effect
- 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
- MIPS instruction set and brief analysis
- SQL 注入绕过(六)
猜你喜欢

Problem solving -- > online OJ (13)

Appium automation test foundation ADB common commands (III)

Roblox剑九之剑二

Schnuka: 3D machine vision inspection system 3D vision inspection application industry

Prompt during packaging: property 'sqlsessionfactory' or 'sqlsessiontemplate'‘

【深度之眼吴恩达机器学习作业班第四期】Regularization正则化总结

cv2.cvtColor

Software testing

Explanation of swing transformer theory

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
随机推荐
Schnuka: automatic tire grabbing installation, 3D visual positioning, automatic robot grabbing
施努卡:什么是视觉定位系统 视觉定位系统的工作原理
Explanation of swing transformer theory
打包时提示: Property ‘sqlSessionFactory‘ or ‘sqlSessionTemplate‘
【深度之眼吴恩达第四期作业班】多元线性回归Linear Regression with multiple variables总结
KingbaseES应对表年龄增长过快导致事务回卷
[translation] swarmed out. Design methods for building modern applications
Matlab Simulink simulation and analysis of power grid sweep frequency
道闸控制器通讯协议
SQL injection bypass (6)
Compiling principle: the king's way
【深度之眼吴恩达机器学习作业班第四期】Logistic Regression 逻辑回归总结
Cv:: mat and Base64 conversion (including picture compression and decompression)
Little white battle pointer (Part 1)
4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
Schnuka: visual positioning system manufacturer what is a visual positioning system
From XX import* is equivalent to from XX import *, and no space is required
【深度之眼吴恩达机器学习作业班第四期】Regularization正则化总结
数组知识点小结
Roblox剑九之剑二