使用Python操作MySQL的小技巧
1、獲取插入數(shù)據(jù)的主鍵id
import pymysql database = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='root', database='test')cursor = database.cursor() for i in range(5): cursor.execute(’insert into test (name) values ('test')’) print(database.insert_id()) database.commit() cursor.close()database.close()
通過db.insert_id()方法可以獲取插入數(shù)據(jù)的主鍵id, 注意一定要在commit之前獲取,否則返回0。
2、創(chuàng)建時間、更新時間
DEFAULT CURRENT_TIMESTAMP--表示當插入數(shù)據(jù)的時候,該字段默認值為當前時間 ON UPDATE CURRENT_TIMESTAMP--表示每次更新這條數(shù)據(jù)的時候,該字段都會更新成當前時間
這兩個操作是mysql數(shù)據(jù)庫本身在維護,可以根據(jù)這個特性來生成【創(chuàng)建時間】和【更新時間】兩個字段,且不需要代碼來維護。
CREATE TABLE `test` ( `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ’創(chuàng)建時間’, `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ’更新時間’) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3、Python插入數(shù)據(jù)庫時字符串中含有單引號或雙引號報錯
可以使用 pymysql.escape_string() 轉(zhuǎn)換
if type(str_content) is str: str_content = pymysql.escape_string(str_content)
4、獲取單個表的字段名和信息的方法
import MySQLdb as mdbimport sys#獲取數(shù)據(jù)庫的鏈接對象con = mdb.connect(’localhost’, ’root’, ’root’, ’test’)with con:#獲取普通的查詢 cursorcur = con.cursor()cur.execute('SELECT * FROM Writers')rows = cur.fetchall()#獲取連接對象的描述信息desc = cur.descriptionprint ’cur.description:’,desc#打印表頭,就是字段名字print '%s %3s' % (desc[0][0], desc[1][0])for row in rows:#打印結(jié)果print '%2s %3s' % row
5、從數(shù)據(jù)庫中把圖片讀出來
import MySQLdb as mdbimport systry:#連接 mysql,獲取連接的對象conn = mdb.connect(’localhost’, ’root’, ’root’, ’test’);cursor = conn.cursor()#執(zhí)行查詢該圖片字段的 SQLcursor.execute('SELECT Data FROM Images LIMIT 1')#使用二進制寫文件的方法,打開一個圖片文件,若不存在則自動創(chuàng)建fout = open(’image.png’,’wb’)#直接將數(shù)據(jù)如文件fout.write(cursor.fetchone()[0])#關閉寫入的文件fout.close()#釋放查詢數(shù)據(jù)的資源cursor.close()conn.close()except IOError, e:#捕獲 IO 的異常 ,主要是文件寫入會發(fā)生錯誤print 'Error %d: %s' % (e.args[0],e.args[1])sys.exit(1)
以上就是使用Python操作MySQL的小技巧的詳細內(nèi)容,更多關于python 操作MySQL的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. 在Android中使用WebSocket實現(xiàn)消息通信的方法詳解2. 淺談python出錯時traceback的解讀3. Python importlib動態(tài)導入模塊實現(xiàn)代碼4. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解5. windows服務器使用IIS時thinkphp搜索中文無效問題6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. Nginx+php配置文件及原理解析8. 利用promise及參數(shù)解構封裝ajax請求的方法9. .NET中l(wèi)ambda表達式合并問題及解決方法10. JSP數(shù)據(jù)交互實現(xiàn)過程解析
