简体   繁体   English

使用Python将.sql文件转换为文本表

[英]Converting .sql file to a text table using Python

I've a .sql file directly exported from phpmyadmin containing data of all the users. 我有一个直接从phpmyadmin导出的.sql文件,其中包含所有用户的数据。 Is it possible to get the list of all the column names and the values from the .sql file without executing the file? 是否可以在不执行文件的情况下从.sql文件中获取所有列名和值的列表?

I'm currently using python's MySQLdb library to execute the .sql file and create the following without a hassle, but I'm trying to skip the execution part and directly convert to .txt file. 我目前正在使用python的MySQLdb库执行.sql文件并轻松创建以下内容,但是我试图跳过执行部分,直接转换为.txt文件。

Example : 范例:

Input file content 输入文件内容

CREATE TABLE IF NOT EXISTS `login_logs` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Username` varchar(20) NOT NULL,
  `Time` int(11) NOT NULL,
  `IP` varchar(20) NOT NULL,
  `Type` enum('Success','Failed') NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 



INSERT INTO `login_logs` (`ID`, `Username`, `Time`, `IP`, `Type`) VALUES
(1, 'User1', 1411318511, '127.0.0.1', 'Failed'),
(2, 'User2', 1411318674, '127.0.0.1', 'Failed'),
(3, 'User3', 1411318683, '127.0.0.1', 'Success'),
(4, 'User12', 1411319092, '127.0.0.1', 'Success'),
(5, 'User3', 1411319112, '127.0.0.1', 'Success');

The output would be something like 输出将是这样的


ID  |  Username  |     Time    |     IP     |  Type
1   |    User1   | 1411318511  | 127.0.0.1  | Failed
1   |    User2   | 1411318674  | 127.0.0.1  | Failed

Which would later be saved in text file. 稍后将其保存在文本文件中。

I understood you'd like to extract the column names and the values from the sql file and write them to a txt file with pipes as column separators. 我了解到您想从sql文件中提取列名和值,并将它们写入带有管道作为列分隔符的txt文件中。 The code below should do the job. 下面的代码可以完成这项工作。 However, it's tailored to exactly your input file example, especially the text structure in the INSERT INTO section. 但是,它是针对您的输入文件示例(特别是INSERT INTO部分中的文本结构)量身定制的。 Once that changes (eg a new line after 'INSERT INTO') it won't work. 一旦更改(例如,在“ INSERT INTO”之后插入新行),它将不起作用。

Hth 高度

#!/usr/bin/python

def remove_stuff(inp_string):
    """ removes some punctuation marks"""
    pm = ['(', ')', '\'', ';', '`']
    # explicitly remove '),' from values lines
    out_string = inp_string.replace('),','')
    for pmark in pm:
        out_string = out_string.replace(pmark, '')
    return out_string

f = open('sql_statements.sql','r')
out = open('table2.txt','w')
line = f.readline()
vals = 0

while line != '':
    if vals == 1:
        values = line.strip()
        values = remove_stuff(values)
        values = values.split(',')
        values = '|'.join(values)
        out.write(values + '\n')
    if 'INSERT INTO' in line.upper():
        col_names = line.split('(')[1]
        col_names = col_names.split(')')[0]
        col_names = remove_stuff(col_names)
        col_names = col_names.split(',')
        col_names = '|'.join(col_names)
        out.write(col_names + '\n')
        vals = 1
    line = f.readline()

f.close()
out.close()

Try this. 尝试这个。

import re
s = open('data.sql','r').read()
s = s[s.find('INSERT'):]
c = re.compile('\((.+),(.+),(.+),(.+),(.+)\)')
f = open('out.txt', 'w')
for item in c.findall(s):
    item = [a.replace("'", "").replace("`","") for a in item]
    f.write('\t|\t'.join(item)+'\n')
f.close()

I'm using regular expressions to match the pattern 我正在使用正则表达式来匹配模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM