python_MySQLdb

獲取列和值python

#!/bin/env python #coding: utf:8 import MySQLdb conn = MySQLdb.connect(host="localhost",user="root",passwd="coship",db="pythondb") cur = conn.cursor() #獲取遊標,打印時只有value cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) #打印時是字典 {列:value} resgeshu = cur.execute("select * from students") #獲取select 個數 data = cur.fetchall() # print data cur.close() conn.close() 

批量插入mysql

#!/bin/env python #coding: utf:8 import MySQLdb conn = MySQLdb.connect(host="localhost",user="root",passwd="coship",db="pythondb") cur = conn.cursor() #列:value parm = [ ('3','hello'), ('4','word'), ] sql = "insert into students(id,name) values(%s,%s)" recount = cur.executemany(sql,parm) conn.commit() print cur.lastrowid #獲取最後自增序列 #data = cur.fetchall() cur.close() conn.close() print recount #print data 

記錄偏移sql

#!/bin/env python #coding: utf:8 import MySQLdb conn = MySQLdb.connect(host="localhost",user="root",passwd="coship",db="pythondb") cur = conn.cursor() #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) #列:value resgeshu = cur.execute("select * from students") #獲取select 個數 data = cur.fetchone() #剛執行獲取第一條記錄,再次調用就獲取下一條 #cur.scroll(-1,mode='relative') #實際位置後退一條記錄 print data data = cur.fetchone() # print data cur.scroll(-1,mode='relative') #實際位置後退一條記錄 #cur.scroll(0,mode='absolute') #回到開頭 data = cur.fetchone() # print data cur.close() conn.close() 

#-*- coding:utf-8 -*- #mysqldb import time, MySQLdb, sys #connect conn = MySQLdb.connect(host="localhost",user="root",passwd="coship",db="pythondb") cursor = conn.cursor() #add sql = "insert into user(name,age) values(%s,%s)" param = ("tom",str(20)) n = cursor.execute(sql,param) print n #更新 sql = "update user set name=%s where Id=9001" param = ("ken") n = cursor.execute(sql,param) print n #查詢 n = cursor.execute("select * from user") for row in cursor.fetchall(): for r in row: print r, print "" #刪除 sql = "delete from user where name=%s" param =("ted") n = cursor.execute(sql,param) print n cursor.close() #關閉 conn.close() 

python鏈接mssql數據庫編碼問題:數據庫

python一直對中文支持的很差,最近老遇到編碼問題,並且幾乎沒有通用的方案來解決這個問題,可是對常見的方法都試過以後,發現仍是能夠解決的,下面總結了經常使用的支持中文的編碼問題(這些方法中可能其中一個就能解決問題,也多是多個組合)。fetch

1. 首先,要保證文件的開頭要加上編碼設置來講明文件的編碼 #encoding=utf-8 2. 而後,在鏈接數據的鏈接參數里加上字符集說明查詢出的結果的編碼,這個不加的後果多是查詢出的漢字字符都是問號 conn=pymssql.connect(server='.',user='', password='',database='MyTest',charset='utf8') 3. 設置python系統的默認編碼(對於文件來講,這招幾乎屢試不爽,呵呵~~import sys reload(sys) sys.setdefaultencoding('utf8')
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息