【问题标题】:Insert into mysql database data of parsing text file插入解析文本文件的mysql数据库数据
【发布时间】:2017-03-14 23:17:01
【问题描述】:

Multi-level parsing text 这个问题中,我问我如何将文件解析为文本文件。 我将条件进一步复杂化,并决定将数据写入 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 |

【问题讨论】:

    标签: mysql ruby-on-rails ruby case-when tiny-tds


    【解决方案1】:

    其实我的版本是可以的,只是我没有考虑到数据库中的数据类型。如果有人知道如何让我的算法更快,请告诉我

    【讨论】:

    • 也许在每个循环之外设置连接?
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多