Mysql的操做python
import MySQLdb try: 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])
防止亂碼sql
須要注意的點:數據庫
1 Python文件設置編碼 utf-8 (文件前面加上 #encoding=utf-8)
2 MySQL數據庫charset=utf-8
3 Python鏈接MySQL是加上參數 charset=utf8
4 設置Python的默認編碼爲fetch
import sys reload(sys) sys.setdefaultencoding("utf-8")
2. hashlib模塊編碼
import hashlib md5 = hashlib.md5() md5.update(str) print md5.hexdigest()