使用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--表示當(dāng)插入數(shù)據(jù)的時候,該字段默認(rèn)值為當(dāng)前時間 ON UPDATE CURRENT_TIMESTAMP--表示每次更新這條數(shù)據(jù)的時候,該字段都會更新成當(dāng)前時間
這兩個操作是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])#關(guān)閉寫入的文件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的小技巧的詳細(xì)內(nèi)容,更多關(guān)于python 操作MySQL的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Android 7.0 運行時權(quán)限彈窗問題的解決2. java實現(xiàn)圖形化界面計算器3. IntelliJ IDEA設(shè)置條件斷點的方法步驟4. IDEA的Mybatis Generator駝峰配置問題5. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法6. 如何利用python和DOS獲取wifi密碼7. Thinkphp3.2.3反序列化漏洞實例分析8. python Xpath語法的使用9. 原生js XMLhttprequest請求onreadystatechange執(zhí)行兩次的解決10. python 批量將PPT導(dǎo)出成圖片集的案例
