python连接mysql实例分享


Posted in Python onOctober 09, 2016

示例一

#coding=UTF-8

import sys
import MySQLdb
import time

reload(sys)
sys.setdefaultencoding('utf-8')

def connectDemo():
  return MySQLdb.Connection("127.0.0.1","root","root","demo",3306,charset="utf8")


if __name__ == '__main__':
  begin=time.time()

  conn=connectDemo()
  cursor = conn.cursor()
  sql="""
    show tables
    """
  count = cursor.execute(sql)
  rows = cursor.fetchall()
  cursor.close()
  conn.close()
  print "========demo库共:%s 张表============" % (count)

  print '耗时:%s 秒' % (time.time()-begin)

示例二

import MySQLdb
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="123456",
db="test")
cursor = conn.cursor()
cursor.execute("select * from hard")
res = cursor.fetchall()
for x in res:
print x
cursor.close()
conn.close()

示例三

1 安装Python的Mysql包

root@10.1.1.45:~# apt-get install python-mysqldb 
root@10.1.1.45:~# python 
Python 2.5.2 (r252:60911, Jan 4 2009, 21:59:32)  
[GCC 4.3.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import MySQLdb 
>>>

  这里导入MySQLdb没有报错,就说明安装成功.

2 下面就可以连接数据库,可以进行增删改操作.

root@10.1.1.45:python# cat create.py  
#!/usr/bin/env python 
#coding=utf-8 
 
#导入相关模块 
import MySQLdb 
 
#建立和mysql数据库的连接 
conn = MySQLdb.connect(host='localhost',user='root',passwd='davehe') 
#获取游标 
curs = conn.cursor() 
#执行SQL,创建一个数据库 
curs.execute("create database pythondb") 
#选择连接哪个数据库 
conn.select_db('pythondb') 
#执行SQL,创建一个表 
curs.execute("create table test(id int,message varchar(50))") 
#插入一条记录 
value = [1,"davehe"] 
curs.execute("insert into test values(%s,%s)",value) 
#插入多条记录 
values = [] 
for i in range(20): 
  values.append((i,'hello mysqldb' + str(i))) 
curs.executemany("insert into test values(%s,%s)",values) 
#提交修改                 
conn.commit() 
#关闭游标连接,释放资源 
curs.close() 
#关闭连接 
conn.close() 
root@10.1.1.45:python# ./create.py

3 下面利用python查看mysql里刚添加的记录.

root@10.1.1.45:python# cat select.py  
#!/usr/bin/env python 
#coding=utf-8 
 
#导入相关模块 
import MySQLdb 
 
#建立和mysql数据库的连接 
conn = MySQLdb.connect(host='localhost',user='root',passwd='hc1226') 
#获取游标 
curs = conn.cursor() 
#选择连接哪个数据库 
conn.select_db('pythondb') 
#查看共有多少条记录 
count = curs.execute('select * from test') 
print "一共有%s条记录" % count 
#获取一条记录,以一个元组返回 
result = curs.fetchone() 
print "当前的一条记录 ID:%s message:%s" % result 
#获取后10条记录,由于之前执行了getchone(),所以游标已经指到第二条记录,下面也就从第二条记录开始返回 
results = curs.fetchmany(10) 
for r in results: 
  print r 
#重置游标位置,0,为偏移量,mode = relative(默认) 
curs.scroll(0,mode='absolute') 
#获取所有记录 
results = curs.fetchall() 
for r in results: 
  print r 
 
#提交修改 
conn.commit() 
#关闭游标连接,释放资源 
curs.close() 
#关闭连接 
conn.close()
root@10.1.1.45:python# ./select.py  
一共有21条记录 
当前的一条记录 ID:1 message:davehe 
(0L, 'hello mysqldb0') 
(1L, 'hello mysqldb1') 
(2L, 'hello mysqldb2') 
(3L, 'hello mysqldb3') 
(4L, 'hello mysqldb4') 
(5L, 'hello mysqldb5') 
(6L, 'hello mysqldb6') 
(7L, 'hello mysqldb7') 
(8L, 'hello mysqldb8') 
(9L, 'hello mysqldb9') 
(1L, 'davehe') 
(0L, 'hello mysqldb0') 
(1L, 'hello mysqldb1') 
(2L, 'hello mysqldb2') 
(3L, 'hello mysqldb3') 
(4L, 'hello mysqldb4') 
(5L, 'hello mysqldb5') 
(6L, 'hello mysqldb6') 
(7L, 'hello mysqldb7') 
(8L, 'hello mysqldb8') 
(9L, 'hello mysqldb9') 
(10L, 'hello mysqldb10') 
(11L, 'hello mysqldb11') 
(12L, 'hello mysqldb12') 
(13L, 'hello mysqldb13') 
(14L, 'hello mysqldb14') 
(15L, 'hello mysqldb15') 
(16L, 'hello mysqldb16') 
(17L, 'hello mysqldb17') 
(18L, 'hello mysqldb18') 
(19L, 'hello mysqldb19')
Python 相关文章推荐
Python 调用DLL操作抄表机
Jan 12 Python
将Emacs打造成强大的Python代码编辑工具
Nov 20 Python
Python简单格式化时间的方法【strftime函数】
Sep 18 Python
Python使用googletrans报错的解决方法
Sep 25 Python
对python3 中方法各种参数和返回值详解
Dec 15 Python
对Python 检查文件名是否规范的实例详解
Jun 10 Python
详解Python利用random生成一个列表内的随机数
Aug 21 Python
使用Python的turtle模块画国旗
Sep 24 Python
python with语句的原理与用法详解
Mar 30 Python
python不到50行代码完成了多张excel合并的实现示例
May 28 Python
通过Python pyecharts输出保存图片代码实例
Nov 25 Python
python 图像增强算法实现详解
Jan 24 Python
Python中运算符"=="和"is"的详解
Oct 08 #Python
Python 爬虫多线程详解及实例代码
Oct 08 #Python
python字符串,数值计算
Oct 05 #Python
python制作企业邮箱的爆破脚本
Oct 05 #Python
python爬取NUS-WIDE数据库图片
Oct 05 #Python
python2.7的编码问题与解决方法
Oct 04 #Python
Python Sqlite3以字典形式返回查询结果的实现方法
Oct 03 #Python
You might like
一个完整的PHP类包含的七种语法说明
2015/06/04 PHP
浅谈laravel框架与thinkPHP框架的区别
2019/10/23 PHP
YUI 读码日记之 YAHOO.lang.is*
2008/03/22 Javascript
JQUERY THICKBOX弹出层插件
2008/08/30 Javascript
jQuery学习笔记之Helloworld
2010/12/22 Javascript
jQuery的运行机制和设计理念分析
2011/04/05 Javascript
jquery配合css简单实现返回顶部效果
2013/09/30 Javascript
JSON中双引号的轮回使用过程中一定要小心
2014/03/05 Javascript
jQuery使用animate创建动画用法实例
2015/08/07 Javascript
解决ajax不能访问本地文件问题(利用js跨域原理)
2017/01/24 Javascript
vue计算属性及使用详解
2018/04/02 Javascript
一次让你了解全部JavaScript的作用域
2019/06/24 Javascript
[02:46]解说DC:感谢430陪伴我们的DOTA2国际邀请赛岁月
2016/06/29 DOTA
Python os模块介绍
2014/11/30 Python
python字符串中的单双引
2017/02/16 Python
python下10个简单实例代码
2017/11/15 Python
python发送邮件脚本
2018/05/22 Python
python3实现网络爬虫之BeautifulSoup使用详解
2018/12/19 Python
python3.6使用tkinter实现弹跳小球游戏
2019/05/09 Python
python3.7环境下安装Anaconda的教程图解
2019/09/10 Python
Win10下python 2.7与python 3.7双环境安装教程图解
2019/10/12 Python
在OpenCV里使用Camshift算法的实现
2019/11/22 Python
浅谈Python中threading join和setDaemon用法及区别说明
2020/05/02 Python
Python用dilb提取照片上人脸的示例
2020/10/26 Python
HTML5的结构和语义(1):前言
2008/10/17 HTML / CSS
西班牙英格列斯百货英国官网:El Corte Inglés英国
2017/10/30 全球购物
泰国第一的化妆品网站:Konvy
2018/02/25 全球购物
《夏夜多美》教学反思
2014/02/17 职场文书
cf收人广告词
2014/03/14 职场文书
《生命的药方》教学反思
2014/04/08 职场文书
推广普通话共筑中国梦演讲稿
2014/09/21 职场文书
暑期社会实践证明书
2014/11/17 职场文书
个人汇报材料范文
2014/12/30 职场文书
2015年主婚人婚礼致辞
2015/07/28 职场文书
教师节领导致辞
2015/07/29 职场文书
配置nginx 重定向到系统维护页面
2021/06/08 Servers