C#操作mysql,以及百万级数据如何快速写入


因为之前的数据都是txt格式的,我们需要自己改成数据库脚本。

当然,也可以直接操作,借用接口写入,在一万条数据以内完全ok,代码如下:

(记得提前添加依赖库)

using System;
using MySql.Data.MySqlClient;
using System.IO;

namespace mysql_earthquake
{
    class mysqlcz
    {
        public mysqlcz()
        {
            FileStream fw = new FileStream("3.txt", FileMode.OpenOrCreate);
            FileStream fw1 = new FileStream("4.txt", FileMode.OpenOrCreate);
            StreamReader r1 = new StreamReader(fw);
            StreamWriter w1 = new StreamWriter(fw1);
            string sql = "";
            string connstr = "data source=localhost;database=earthquake;user id=root;password=000000;pooling=false;charset=utf8";
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                conn.Open();
                string sql3 = "INSERT INTO earthquake.earthquake_count(start_time,intensity,longitude,latitude,depth,place)VALUES";
                for(int i=1;i<=1900391;i++)
                {
                    string s1 = r1.ReadLine();
                    string s2 = r1.ReadLine();
                    string s3 = r1.ReadLine();
                    string s4 = r1.ReadLine();
                    string s5 = r1.ReadLine();
                    string s6 = r1.ReadLine();
                    sql =sql3+"('"+s1+"',"+s2+","+s3+","+s4+","+s5+",'"+s6+"');";
                    w1.WriteLine(sql);
                    MySqlCommand cmd3 = new MySqlCommand(sql, conn);
                    int s = cmd3.ExecuteNonQuery();
                    if (s == 0)
                    {
                        Console.WriteLine(i);
                        Console.WriteLine("false");
                    }
                }
                
                conn.Close();
            }
            Console.ReadLine();
        }


    }
    class Program
    {
        static void Main(string[] args)
        {
            mysqlcz mt = new mysqlcz();
        }
    }
}

以上代码中同时包含了直接调用接口写,以及把脚本指令写进4.txt中等操作,事实证明直接写速度太慢,200万条需要写一星期。

如何快速操作写进mysql呢?

0、将上文生成的4.txt重命名为4.sql

1、修改my.ini配置文件下innodb_buffer_pool_size值
     尽可能做到设置值为系统内存的30%,然后重启服务,若重启出现报错,请把该值改小,直至重启成功。
     注:我修改后,出现无法启动问题,要求编码是UTF-8,可以使用notepad++修改回来

2、修改innodb自动提交为off(这是临时的,下次重启服务会恢复原值on)
     方式:cmd进入到MySQL的bin目录下,输入
     set autocommit=0;

3、mysql可视化界面或命令行,输入:set global innodb_flush_log_at_trx_commit = 0;

4、利用bat文件将改sql文件导入到MySQL,bat文件和sql文件同时放到MySQL的bin目录下,点击bat脚本运行
     注:bat脚本中,用户名root,密码000000,数据库名earthquake,如有差异适当修改。

附:.bat脚本代码

@echo off
set host=127.0.0.1
set user=root
set password=000000
set filename=4
set dbname=earthquake

cd %~dp0
echo 开始更新
echo %TIME%
mysql -h %host% -u %user% -p%password% %dbname%< %filename%.sql
echo %TIME%
echo 成功完成更新
pause

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM