在python中实现对数据库的访问和增删改查操作。
本文采用的是
# -*- coding: utf-8 -*-
__author__ = 'jason'
import mysql.connector
import os, sys, string
#connect to mysql
try:
conn = mysql.connector.connect(host='127.1.1.6', user='hello', passwd='124415', db='youDB')
except Exception, e:
print e
sys.exit()
#get cursor
cursor = conn.cursor()
#select table
sql = 'select count(*) from tbl_HashSortInfo1 where UC_CalVersion>0'
cursor.execute(sql)
alldata = cursor.fetchall()
if alldata:
for rec in alldata:
print rec[0]
cursor.close()
conn.close()
根据select的各个字段结果,逐一打印出来。
# -*- coding: utf-8 -*-
__author__ = 'jason'
import mysql.connector
import os, sys, string
#connect to mysql
try:
conn = mysql.connector.connect(host='127.1.1.6', user='hello', passwd='124415', db='youDB')
except Exception, e:
print e
sys.exit()
#get cursor
cur = conn.cursor()
#select table
sql = 'select ID,Hash,Hash1,Hash2,Hash3,TimeLength,Version from tbl_Hash where Version>0 limit 100'
cur.execute(sql)
alldata = cur.fetchall()#接收全部的返回结果行,会不会过于占用内存???如果结果很大呢??
#alldatae的结果是一个list
alllen = len(alldata)
print 'alldata length is ',alllen
numrows = int(cur.rowcount)# 使用cur.rowcount获取结果集的条数
print(numrows)#结果是100
print(type(alldata))#类型是list
#print(alldata)
for id in alldata:
#遍历元组
for i in range(len(id)):
print id[i],
print '\r'
cur.close()
conn.close()
输出结果是按行排列,每行中各个字段又以空格进行分隔。同时,这里需要注意的是,print是自动换行的,想要实现,上述效果,需要在print后面加个逗号,并在每行结束之后,加个回车。
采用逐行读取的方式,对应的方式为fetchone。
# -*- coding: utf-8 -*-
__author__ = 'jason'
import mysql.connector
import os, sys, string
#connect to mysql
try:
conn = mysql.connector.connect(host='127.1.1.6', user='hello', passwd='124415', db='youDB')
except Exception, e:
print e
sys.exit()
#get cursor
cur = conn.cursor()
#select table
sql = 'select ID,Hash,Hash1,Hash2,Hash3,TimeLength,Version from tbl_Hash where Version>0 limit 100'
cur.execute(sql)
#alldatae的结果是一个list
numrows = int(cur.rowcount)# 使用cur.rowcount获取结果集的条数
print('未读取数据时的rowcount值:',numrows)#这是由于未读取数据,所以游标还在数据之外,所以是-1
data = cur.fetchone()
print 'fetchone之后的rowcount值',cur.rowcount
data = cur.fetchone()
print 'fetchone之后的rowcount值',cur.rowcount
while data:
data = cur.fetchone()
if data != None:
#print data
for i in range(len(data)):
print data[i],
print '\r'
# if alldata:
# for i in len(alldata):
# print rec[i][j]
cur.close()
conn.close()
注意这种方法由于数据是一个个取出来的,所以数据没有取完之前,是不可以再次使用cur对象进行其他类似,insert操作的,会提示“unread results”的错误。这是由于连接对象 cur在未取完数据的时候,又在其他地方使用了。这时候可以考虑用fetchall方式进行数据的读取。在其他的情况下可以通过设置buffered选项,cursor = cnx.cursor(buffered=True)使得数据结果立刻被读取。
使用字典cursor取得结果集(可以使用表字段名字访问值)
# -*- coding: utf-8 -*-
__author__ = 'jason'
import mysql.connector
import os, sys, string
#connect to mysql
try:
conn = mysql.connector.connect(host='127.1.1.6', user='hello', passwd='124415', db='youDB')
except Exception, e:
print e
sys.exit()
#get cursor
#获取连接上的字典cursor,注意获取的方法,
#每一个cursor其实都是cursor的子类
cur = conn.cursor(dictionary=True)#主要是这里!!!!!
#select table
sql = 'select ID,Hash,Hash1,Hash2,Hash3,TimeLength,Version from tbl_Hash where Version>0 limit 100'
cur.execute(sql)
#alldatae的结果是一个list
numrows = int(cur.rowcount)# 使用cur.rowcount获取结果集的条数
data = cur.fetchone()
while data:
data = cur.fetchone()
if data != None:
print data["ID"],data["Hash"],data["Hash1"],data["Hash2"],data["Hash3"],data["TimeLength"],data["Version"]
cur.close()
conn.close()
补充,打印表各个字段的信息:
import mysql.connector
from mysql.connector import FieldType
import os, sys, string
#connect to mysql
try:
conn = mysql.connector.connect(host='127.1.1.6', user='hello', passwd='124415', db='youDB')
except Exception, e:
print e
sys.exit()
#get cursor
#获取连接上的字典cursor,注意获取的方法,
#每一个cursor其实都是cursor的子类
cur = conn.cursor(dictionary=True)
#select table
sql = 'select ID,UC_FileHash,UC_LyricId,UC_Singer,UC_Song,UC_TimeLength,UC_CalVersion from tbl_tblInfo1 where UC_CalVersion>0 limit 10'
cur.execute(sql)
#获取连接对象的描述信息
desc = cur.description#主要是这里!!!
#返回的是元组组成的
print 'cur.description:',desc
for i in range(len(cur.description)):
print("Column {}:".format(i+1))
desc = cur.description[i]
print(" column_name = {}".format(desc[0]))
print(" type = {} ({})".format(desc[1], FieldType.get_info(desc[1])))
print(" null_ok = {}".format(desc[6]))
print(" column_flags = {}".format(desc[7]))
该方法更安全方便。
有两种方式可以
方式1:
import mysql.connector
cnx = mysql.connector.connect(database='employees')
cursor = cnx.cursor(prepared=True)
方式2:
import mysql.connector
from mysql.connector.cursor import MySQLCursorPrepared
cnx = mysql.connector.connect(database='employees')
cursor = cnx.cursor(cursor_class=MySQLCursorPrepared)
具体例子如下:
# -*- coding: utf-8 -*-
__author__ = 'jason'
import mysql.connector
import os, sys, string
#connect to mysql
try:
conn = mysql.connector.connect(host='127.1.1.6', user='hello', passwd='124415', db='youDB')
except Exception, e:
print e
sys.exit()
#get cursor
#获取连接上的字典cursor,注意获取的方法,
#每一个cursor其实都是cursor的子类
cur = conn.cursor(prepared=True)#注意这里
cur = conn.cursor(dictionary=True)#请注意下两者的先后顺序,看官们可以尝试改变先后顺序?
#这里可以通过写一个可以组装的sql语句来进行
#select table
sql = 'select ID,UC_FileHash,UC_LyricId,UC_Singer,UC_Song,UC_TimeLength,UC_CalVersion from tblInfo1 where UC_CalVersion>%s limit %s'
cur.execute(sql,(10,4))#注意这里!!!!
data = cur.fetchone()
while data:
if data != None:
print data["ID"],data["UC_FileHash"],data["UC_LyricId"],data["UC_Singer"],data["UC_Song"],data["UC_TimeLength"],data["UC_CalVersion"]
data = cur.fetchone()
cur.close()
conn.close()
结果只会是打印出4条结果记录!
添加记录例子:
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
# 事务的特性1、原子性的手动提交
conn.commit()
cur.close()
conn.close()
except mysql.connector.Error as err:
# 如果出现了错误,那么可以回滚,就是上面的三条语句要么执行,要么都不执行
conn.rollback()
print("Something went wrong: {}".format(err))
# 关闭数据库连接
db.close()
在调用 execute() 方法之后,需要调用MySQLConnection对象中的commit()方法,使得delete和update生效。其他的是一样的。