-
Mysql的操作
import MySQLdbtry: conn = MySQLdb.connect(host='localhost', user='root', passwd='123', charset='utf8', db='python') cur = conn.cursor() #选库 conn.select_db('python') #删除表 cur.execute('drop table if jrj exists') #单行写入 para = ('aa', 'bb', '2015') #或者 para = ['aa', 'bb', '2015'] n = cur.execute('INSERT INTO jrj(title, url, add_date) VALUES(%s, %s, %s)', para) #一次写入多行 para = [['a', 'aaa', '2015'], ['b', 'bbb', '2015'], ['c', 'ccc', '2015']] n = cur.executemany('INSERT INTO jrj(title, url, add_date) VALUES(%s, %s, %s)', para) # n都返回插入的数据条数 #更新, 删除等格式 param = ("zzz") n = cur.execute("update user set name=%s where name='aaa'", param) #查询 n = cur.execute('select * from jrj') #n 返回的是查询的数据条数 #取一行 print cur.fetchone() #取多行 for row in cur.fetchall(): print row print row[0] cur.close() conn.commit() conn.close() except MySQLdb.Error,e: print 'Mysql error: %s %s' %(e.args[0], e.args[1])
防止乱码
需要注意的点:
1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
2 MySQL数据库charset=utf-8 3 Python连接MySQL是加上参数 charset=utf8 4 设置Python的默认编码为import sysreload(sys)sys.setdefaultencoding("utf-8")
2. hashlib模块
import hashlibmd5 = hashlib.md5()md5.update(str)print md5.hexdigest()