2015-07-21 45 views
1

我很困惑我需要編寫一個python /任何腳本,這需要處理以下情況的方法。解析文本數據並在MySQL中插入

我產生從服務器列名,時間戳,服務器名和列值

cpunumber 1437501780 l09fr01 40.0 
cpunice 1437501780 l09fr01 0.0 
cpusystem 1437501780 l09fr01 0.0 
cpuwait 1437501780 l09fr01 0.0 
cpuuser 1437501780 l09fr01 1.0 
cpudile 1437501780 l09fr01 0.0 

,我需要插入這些值的表中的文本文件,下面給出。加載id是我將在程序中唯一填充的東西。解析上述信息並將其加載到表中的最佳方法是什麼?

CREATE TABLE `test`.`cpu_util_all` (
`loadid` INT NOT NULL, 
    `servername` VARCHAR(45) NOT NULL, 
    `date_time` DATETIME NOT NULL, 
    `cpu_number` DECIMAL(10,2) NULL, 
    `cpu_user` DECIMAL(10,2) NULL, 
    `cpu_nice` DECIMAL(10,2) NULL, 
    `cpu_system` DECIMAL(10,2) NULL, 
    `cpu_wait` DECIMAL(10,2) NULL, 
    `cpu_idle` DECIMAL(10,2) NULL, 
    PRIMARY KEY (`loadid`, `servername`, `date_time`,`cpu_user`)); 

回答

1

您可以使用pandas讀取這樣的數據,並將其寫入SQL爲好。

import pandas as pd 
import sqlite3 

## Tweak the options here to match the exact file format. 
x = pd.read_table('test.txt') 
## add column names (not necessary if the file has a header) 
x.names = ['loadid','servername','date_time','cpu_number','cpu_nice','cpu_system','cpu_wait','cpu_idle'] 

## create SQL connection. 
con = sqlite3.connect('test.db',) 
## tweak the options here to get the keys and constraints. 
x.to_sql('test', con) 

你可以閱讀更多關於使用熊貓閱讀和寫作here

相關問題