一、说明:
(1)在linux系统下通过shell脚本执行python脚本
(2)txt文件的编码为utf8
(3)插入window系统中的sql server 2000
二、代码说明
(1)首先创建表结构
-
CREATE TABLE [dbo].[POWER_METER_CFG_MV] (
-
[STATION_ID] [int] NOT NULL ,
-
[DEVICE_ID] [int] NULL ,
-
[DATA_OBJECT_ID] [int] NULL ,
-
[OBJECT_NAME] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL
-
)
(2)txt文件内容
-
366,207,7089,油机输入开关
-
-
363,299,10236,油机输入开关
-
-
287,286,9773,主设备2开关
-
-
287,284,9685,机房空调2开关
-
-
287,285,9729,油机输入开关
-
-
365,210,7247,主设备2开关
-
-
,104,3557,市电总输入开关
-
-
,105,3601,主设备1开关
(3)配置连接数据库的ip,用户名,密码,数据库名文件:config.py
-
import csv
-
import sys
-
-
db_host = '192.168.0.33'
-
db_name = 'EnergyCfg'
-
db_username = 'sa'
-
db_password = ''
(4)连接数据库python模块代码文件:db.py
-
import os
-
import pymssql
-
import config
-
-
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
-
db_pool = None
-
-
def getPool():
-
global db_pool
-
if(db_pool == None):
-
db_pool = pymssql.connect(config.db_host,user=config.db_username,password=config.db_password,database=config.db_name, charset='cp936')
-
return db_pool
-
-
def getConnection():
-
return getPool()
-
-
def releaseConnection(conn):
-
return getPool().close()
由于sql server 2000是属于中文编码,因此在连接时要指定编码,如:
charset='cp936'
(5)插入数据库代码文件:insert_config.py
-
#!/bin/env python
-
# -*- coding: utf-8 -*-
-
import csv
-
import sys
-
import datetime
-
import db
-
-
def init():
-
infile = sys.stdin
-
outfile = sys.stdout
-
if(len(sys.argv) > 1) :
-
infile = open(sys.argv[1], 'rb')
-
reader = csv.reader(infile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL, skipinitialspace=True)
-
writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL, skipinitialspace=True)
-
return reader, writer
-
-
def insert2(lst,cursor):
-
cur=cursor.cursor()
-
for value in lst:
-
sql="""insert into POWER_METER_CFG_MV (STATION_ID,DEVICE_ID, DATA_OBJECT_ID,OBJECT_NAME)VALUES(%d,%d,%d,'%s')""" % (value[0],value[1],value[2],value[3])
-
cur.execute(sql)
-
conn.commit()
-
cur.close()
-
-
if __name__ == '__main__':
-
reader, writer = init()
-
conn = db.getConnection()
-
lst=[]
-
try:
-
print datetime.datetime.now()
-
for row in reader:
-
if row[0] and row[1] and row[2] and row[3]:
-
alarm = (int(row[0]), int(row[1]), int(row[2]),row[3].decode("utf-8").encode('gbk'))
-
lst.append(alarm)
-
insert2(lst,conn)
-
print datetime.datetime.now()
-
except Exception:
-
conn.rollback()
-
raise
-
finally:
-
db.releaseConnection(conn)
由于txt文件编码是utf8的,因此需要先使用
decode("utf-8")进行解码,然后再使用encode('gbk')转换成gbk编码
(6)执行py文件的shell脚本文件:
insert_config.py
-
# !/bin/sh
-
-
insert_config() {
-
cat POWER_METER_CFG |python insert_config.py
-
}
-
insert_config
先通过系统命令cat
POWER_METER_CFG 将内容输出到终端,然后insert_config.py再从终端读取内容。
代码文件:
insert.rar
阅读(2660) | 评论(0) | 转发(0) |