python_MySQLdb

获取列和值

#!/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() 

批量插入

#!/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 

记录偏移

#!/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一直对中文支持的不好,最近老遇到编码问题,而且几乎没有通用的方案来解决这个问题,但是对常见的方法都试过之后,发现还是可以解决的,下面总结了常用的支持中文的编码问题(这些方法中可能其中一个就能解决问题,也可能是多个组合)。

1. 首先,要保证文件的开头要加上编码设置来说明文件的编码
#encoding=utf-8
2. 然后,在连接数据的连接参数里加上字符集说明查询出的结果的编码,这个不加的后果可能是查询出的汉字字符都是问号 conn=pymssql.connect(server='.',user='', password='',database='MyTest',charset='utf8') 3. 设置python系统的默认编码(对于文件来说,这招几乎屡试不爽,呵呵~~import sys reload(sys) sys.setdefaultencoding('utf8')

转载于:https://www.cnblogs.com/Sinjon-Liu/p/8125318.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值