[python]操作Mysqlデータベース

2525 ワード

#!/usr/bin/python
#InsertData file1 file2
#file_name like sh600115_2014-12-29.txt
import sys
import MySQLdb
import csv
import datetime

mysql_host='localhost'
mysql_user='stock'
mysql_passwd='stock'
mysql_db='stock'
file_index = 1

conn=MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_passwd,db=mysql_db)
cur=conn.cursor()

while file_index < len(sys.argv):
	file_name=sys.argv[file_index]
	file_index=file_index+1

	mysql_table = file_name.split('_')[0]
	file_date = file_name.split('_')[1].split('.')[0]
	
	sql_str='create table if not exists '+mysql_table
	sql_str=sql_str+'(trade_time datetime not null, trade_price decimal(6,2) not null, price_var decimal(6,2) not null, trade_num int(20) not null, type char(1) not null)'
	cur.execute(sql_str)
	
	print "insert file: " + file_name + " into " + mysql_db + "." + mysql_table
	
	date_start=datetime.datetime.strptime(file_date,'%Y-%m-%d')
	date_end=date_start+datetime.timedelta(days=1)
	sql_str = 'select count(*) from ' + mysql_table +' where trade_time>' + "'" + date_start.strftime('%Y-%m-%d') + ' 0:0:0' + "'"
	sql_str = sql_str + 'and trade_time<' + "'" + date_end.strftime('%Y-%m-%d') + ' 0:0:0' + "'"
	cur.execute(sql_str)
	if cur.fetchone()[0]!=0:
		continue

	csvfile=file(file_name,'rb');
	reader=csv.reader(csvfile,delimiter='\t')
	for line in reader:
		if reader.line_num==1:
			continue
		insert_str = 'insert into '
		insert_str = insert_str + mysql_table +'(trade_time,trade_price,price_var,trade_num,type) values('
		insert_str = insert_str + "'" + file_date + ' '
		insert_str = insert_str + line[0] + "'"
		insert_str = insert_str + ',' + line[1]
		insert_str = insert_str + ',' + line[2]
		insert_str = insert_str + ',' + line[3]
		if len(line[5]) != 4:
			insert_str = insert_str + ',' + "'" + 'N' + "'" + ')'
		elif line[5][1]=='\xf4':
			insert_str = insert_str + ',' + "'" + 'S' + "'" + ')'
		else:
			insert_str = insert_str + ',' + "'" + 'B' + "'" + ')'
		#print insert_str
		cur.execute(insert_str)
conn.commit()
cur.close()
conn.close()