0
在這個問題Multi-level parsing text我問我如何解析文件到一個文本文件。 我進一步複雜的條件,決定寫數據到MySQL數據庫。 原始數據是一樣的。插入到mysql數據庫解析文本文件的數據
我有一個文本文件,未來包含:
Head 1
Subhead 1
a 10
b 14
c 88
Subhead 2
a 15
b 16
c 17
d 88
Subhead 3
a 55
b 36
c 87
Head 4
Subhead 1
r 32
t 55
s 79
r 22
t 88
y 53
o 78
p 90
m 44
Head 53
Subtitle 1
y 22
b 33
Subtitle 2
a 88
g 43
r 87
Head 33
Subhead 1
z 11
d 66
v 88
b 69
Head 32
Subhead 1
n 88
m 89
b 88
Subhead 2
b 88
m 43
現在我需要構建這個文本下一班飛機。我想寫這個數據到mysql數據庫。 我的行爲:
require 'tiny_tds'
current_head = ""
current_sub = ""
res = []
@host = 'server'
@user = 'user'
@pass = 'pass'
lines.each do |line|
case line
when /Head \d+/
current_head = line
when /Subhead/
current_sub = line
when /\w{1} 88/
num = line
res << "#{current_head}, #{current_sub}, #{num}"
conn = TinyTds::Client.new(:host => @host, :username => @user, :password => @pass)
insert_string = "insert into table (head, sub, num) VALUES (#{res})"
conn.execute(insert_string)
end
end
結果,我可以只插入一行到數據庫中。另外,插入過程非常緩慢,我怎樣才能加快這個過程?
我需要這個結果到數據庫:
head | Sub | num |
_________________________
Head 1 | Subhead 1| c 88 |
Head 1 | Subhead 2| d 88 |
Head 4 | Subhead 1| t 88 |
Head 53| Subhead 2| a 88 |
Head 33| Subhead 1| v 88 |
Head 32| Subhead 1| n 88 |
Head 32| Subhead 1| b 88 |
Head 32| Subhead 2| b 88 |
也許每個循環之外的連接設置? – Fallenhero