因為之前的數據都是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