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='', 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', '', 'testdb')
cursor = conn.cursor(cursorclass=mdb.cursors.DictCursor)
sql = """select count(*) from tablename;"""
cursor.execute(sql)
r = cursor.fetchall()
print(r)

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

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

解决方法:

 

最新文章

  1. ASP.NET用QQ,网易发送邮件以及添加附件
  2. big-endian和little-endian
  3. SSH三大框架的JAR包下载地址
  4. 神奇的 CURL 命令
  5. oracle 卸载和安装
  6. OpenCV2.3.1在Win7+VS2010下的配置过程(转)
  7. VS2010 密钥问题
  8. [tty与uart]理解线路规程的作用
  9. Seafile V4.1 安装笔记
  10. AngularJS 拦截器和好棒例子
  11. bzoj 1800: [Ahoi2009]fly 飞行棋 暴力
  12. Java设计模式(二)抽象工厂模式
  13. 基于WAMP的Crossbario 安装入门
  14. .net下的缓存技术
  15. 微信硬件平台(九) 自己的服务器从微信获取token并保存txt
  16. python实现求最大公约数与最小公倍数
  17. #13 让代码变得Pythonic
  18. vs问题集
  19. zookeeper集群扩容/下线节点实践
  20. 【DB】部分MySQL操作记录

热门文章

  1. zookeeper做集群后启动不了,大部分原因是防火墙未关闭
  2. 小白都能看明白的VLAN原理解释
  3. 让Elasticsearch集群冷热分离、读写分离【转】
  4. 浅析LRC歌词文件
  5. 建站工具Hexo
  6. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project demo: Fatal error com piling: 无效的标记: -parameters
  7. [原]win10下编译lua5.3.4
  8. SQLSERVER查询那个表里有数据
  9. 10.Oracle Golden Date(ogg)的搭建和管理
  10. C_C++变量命名规则