python使用MySQLdb实现连接数据库Mysql

python实现连接数据库mysql的步骤:

一、引入MySQLdb

二、获取与数据库的连接

三、执行SQL语句和存储过程

四、关闭数据库连接

 

1.什么是MySQLdb?

MySQLdb是用于python连接mysql数据库的接口;

2.连接数据库前确认事项:

(1)数据库名:testdb

(2)数据库的用户名:root  密码为:123456

(3)数据库IP:127.0.0.1

(4)数据库端口:3306

(5)查询数据库tablename表的记录数

3.给出代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='testsb', charset='utf8' )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()
sql = """select count(*) from tablename;"""
# 使用execute方法执行SQL语句 
cursor.execute(sql)
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Database version : %s " % data

# 关闭数据库连接
db.close()

4.或者是:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb as mdb

# 连接数据库
# conn = mdb.connect('localhost', 'root', 'root')

# 也可以使用关键字参数
conn = mdb.connect(host="127.0.0.1",port=3306,user='root',passwd='123456',db='testdb',charset='utf8')

# # 也可以使用字典进行连接参数的管理
#
config = { # 'host': '127.0.0.1',
#
'port': 3306,
#
'user': 'root',
#
'passwd': 'root',
#
'db': 'test',
#
'charset': 'utf8'
#
}
#
conn = mdb.connect(**config)

# 如果使用事务引擎,可以设置自动提交事务,或者在每次操作完成后手动提交事务conn.commit()
conn.autocommit(1)

# conn.autocommit(True)

# 使用cursor()方法获取操作游标
cursor = conn.cursor()

# 因该模块底层其实是调用CAPI的,所以,需要先得到当前指向数据库的指针。
TABLE_NAME = 'bsj'
try:
  sql = """select count(*) from vehicle;"""
  cursor.execute(sql)
  # 返回单个的元组,也就是一条记录(row),如果没有结果则返回None
  result=cursor.fetchone()

  print(result)

  # 如果没有设置自动提交事务,则这里需要手动提交一次
  conn.commit()

except:
  import traceback 
  traceback.print_exc()

  # 发生错误时会滚
  conn.rollback()

finally:
  # 关闭游标连接
  cursor.close()

  # 关闭数据库连接
  conn.close()

5.注意事项:

如果select本身取的时候有多条数据时:

cursor.fetchone():将只取最上面的第一条结果,返回单个元组如('id','title'),然后多次使用cursor.fetchone(),依次取得下一条结果,直到为空。

cursor.fetchall() :将返回所有结果,返回二维元组,如(('id','title'),('id','title')),
---------------------

如果select本身取的时候只有一条数据时:

cursor.fetchone():将只返回一条结果,返回单个元组如('id','title')。

cursor.fetchall() :也将返回所有结果,返回二维元组,如(('id','title'),)

备注:其中的id和title为具体的内容

python在mysql在使用fetchall或者是fetchone时,综合起来讲,fetchall返回二维元组(元组中含有元组),fetchone只返回一维元组。

 

6.MySQLsb默认查询结果都是返回元组(tuple),通过使用不同的游标可以改变输出格式,这里传递一个cursors.DictCursor参数

import MySQLdb.cursors

conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()
sql = """select count(*) from tablename;"""
cursor.execute(sql)
r = cursor.fetchall()
print(r)
# 当使用位置参数或字典管理参数时,必须导入MySQLdb.cursors模块

# 也可以用下面的写法
import MySQLdb as mdb
conn  = mdb.connect('127.0.0.1', 'root', '123456', 'testdb')
cursor = conn.cursor(cursorclass=mdb.cursors.DictCursor)
sql = """select count(*) from tablename;"""
cursor.execute(sql)
r = cursor.fetchall()
print(r)

使用MySQLdb取回大结果集的缺点:

普通的操作无论是fetchall()还是fetchone()都是先将数据载入到本地再进行计算,大量的数据会导致内存资源消耗光。

解决方法:

 

转载于:https://www.cnblogs.com/yfacesclub/p/10418367.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值