#-*-Coding:utf-8-*-
"" "
@version: python2.7.8
@author: Xiangguosun
@contact: sunxiangguodut@qq.com
@file: connectdb.py
@time: 2016/12/28 16:12 "" "
import mysqldb
Import Time
def connectdb (): While
True:
try:
db = MySQLdb.connect ("localhost", "root", "root", "Douban") Return
db
except mysqldb.error,e:
print E.args, "(CONNECTDB) we'll try again after seconds ..."
Time.sleep (10)
The following is an operation on the database
#!/usr/bin/env python #-*-coding:utf-8-*-"" "@version: python2.7.8 @author: Xiangguosun @contact: Sunxiangguodut@qq. COM @file: dbfunction.py @time: 2017/2/10 11:08 @software: Pycharm "" "Import sys from CONNECTDB import connectdb reload (s YS) sys.setdefaultencoding (' Utf-8 ') def Fun (tablename): db = Connectdb () cursor = Db.cursor () print "Start TR
Ansform ", TableName," ... "sql =" Select COUNT (*) as repetitions, uid, time "\" from "+ tablename +" "\ "GROUP by UID, time" \ "have repetitions > 1" curs
Or.execute (sql) an = Cursor.fetchall () print "Duplicate data:", Len (a) sql = "Select uid, ' time '" \ ' From ' + tablename + ' \ ' GROUP by uid, time ' cursor.execute (SQL) print create tmp ... ' sql = "CREATE TABLE tmp SELECT ' uid ', ' likers_count ', ' time ', ' url ', ' comments_count ', ' Activity ', ' type ', ' content ', ' crawtime ' "\" from "+ TableName + "GROUP by uid, time" cursor.execute (SQL) print "Create TMP done!" Print "drop table" +tablename+ ... "sql =" drop table "+ tablename cursor.execute (SQL) Print" drop table "+ta
Blename+ "done!"
Print "Rename table tmp as" +tablename+ ... "sql = ALTER table tmp Rename to" + tablename Cursor.execute (SQL)
Print "Rename done!" Print "Add key ..." sql = "ALTER TABLE" + tablename + "Add PRIMARY key (' uid ', ' time ')" Cursor.execute (SQL) PR
int "Key added done!"
Print "succeed!" db = Connectdb () for I in range (1,200): Fun ("Userlifestream_" +str (i)) print ' All done! '
Note the use of escape symbols, especially in SQL statement group
There is also an increase in the joint primary key: No conversion characters will be the error
The escape operator is the one on the keyboard that corresponds to the ~ key
"Add Key ..."
sql = "ALTER TABLE" + tablename + "Add PRIMARY key (' uid ', ' time ')"
cursor.execute (SQL)
"Key added done!"