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处理文本文件并生成指定格式的文件
Jul 31 Python
Python简单实现子网掩码转换的方法
Apr 13 Python
完美解决安装完tensorflow后pip无法使用的问题
Jun 11 Python
对pandas数据判断是否为NaN值的方法详解
Nov 06 Python
浅谈Python基础—判断和循环
Mar 22 Python
Python箱型图绘制与特征值获取过程解析
Oct 22 Python
使用python实现微信小程序自动签到功能
Apr 27 Python
Pandas实现一列数据分隔为两列
May 18 Python
完美解决jupyter由于无法import新包的问题
May 26 Python
Python实现快速大文件比较代码解析
Sep 04 Python
分析Python感知线程状态的解决方案之Event与信号量
Jun 16 Python
全网非常详细的pytest配置文件
Jul 15 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获取栏目的所有子级和孙级栏目的ID号示例
2014/04/01 PHP
让ThinkPHP支持大小写url地址访问的方法
2014/10/31 PHP
php实现四舍五入的方法小结
2015/03/03 PHP
详解PHP文件的自动加载(autoloading)
2018/02/04 PHP
PHP性能测试工具xhprof安装与使用方法详解
2018/04/29 PHP
PHP实现文件上传与下载
2020/08/28 PHP
什么是json和jsonp,jQuery json实例详详细说明
2012/12/11 Javascript
一个简单的动态加载js和css的jquery代码
2014/09/01 Javascript
超炫的jquery仿flash导航栏特效
2014/11/11 Javascript
node.js中的http.request方法使用说明
2014/12/14 Javascript
每天一篇javascript学习小结(RegExp对象)
2015/11/17 Javascript
轮播图组件js代码
2016/08/08 Javascript
利用JS轻松实现获取表单数据
2016/12/06 Javascript
opencv 识别微信登录验证滑动块位置
2018/08/07 Javascript
原生JS实现简单的无缝自动轮播效果
2018/09/26 Javascript
详解适配器在JavaScript中的体现
2018/09/28 Javascript
nodejs初始化init的示例代码
2018/10/10 NodeJs
原生JS封装拖动验证滑块的实现代码示例
2020/06/01 Javascript
实例讲解React 组件
2020/07/07 Javascript
[39:00]Optic vs VP 2018国际邀请赛淘汰赛BO3 第三场 8.24
2018/08/25 DOTA
如何在sae中设置django,让sae的工作环境跟本地python环境一致
2017/11/21 Python
python的exec、eval使用分析
2017/12/11 Python
django+xadmin+djcelery实现后台管理定时任务
2018/08/14 Python
对Python 3.5拼接列表的新语法详解
2018/11/08 Python
在python中利用GDAL对tif文件进行读写的方法
2018/11/29 Python
Python3中的最大整数和最大浮点数实例
2019/07/09 Python
Python 调用 Windows API COM 新法
2019/08/22 Python
Django实现任意文件上传(最简单的方法)
2020/06/03 Python
Python析构函数__del__定义原理解析
2020/11/20 Python
详解python的变量缓存机制
2021/01/24 Python
python如何实现递归转非递归
2021/02/25 Python
怎样实现H5+CSS3手指滑动切换图片的示例代码
2019/05/05 HTML / CSS
护理工作感言
2014/01/16 职场文书
保管员岗位职责
2015/02/14 职场文书
nginx反向代理配置去除前缀案例教程
2021/07/26 Servers
MySQL控制流函数(-if ,elseif,else,case...when)
2022/07/07 MySQL