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模块smtplib实现纯文本邮件发送功能
May 22 Python
python设置值及NaN值处理方法
Jul 03 Python
python2.7实现邮件发送功能
Dec 12 Python
使用Python进行体育竞技分析(预测球队成绩)
May 16 Python
Django框架模板文件使用及模板文件加载顺序分析
May 23 Python
在Pandas中处理NaN值的方法
Jun 25 Python
python gdal安装与简单使用
Aug 01 Python
Python实现TCP探测目标服务路由轨迹的原理与方法详解
Sep 04 Python
Python进阶之使用selenium爬取淘宝商品信息功能示例
Sep 16 Python
Python for i in range ()用法详解
Sep 18 Python
判断Threading.start新线程是否执行完毕的实例
May 02 Python
Python中的None与 NULL(即空字符)的区别详解
Sep 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连接MySQL代码的参数说明
2008/06/07 PHP
php中利用post传递字符串重定向的实现代码
2011/04/21 PHP
PHP文件去掉PHP注释空格的函数分析(PHP代码压缩)
2013/07/02 PHP
smarty内置函数capture用法分析
2015/01/22 PHP
php创建、获取cookie及基础要点分析
2015/01/26 PHP
jquery实现select选中行、列合计示例
2014/04/25 Javascript
AngularJS iframe跨域打开内容时报错误的解决办法
2015/01/26 Javascript
jQuery实现高亮显示网页关键词的方法
2015/08/07 Javascript
理解javascript闭包
2015/12/15 Javascript
详解Angular.js指令中scope类型的几种特殊情况
2017/02/21 Javascript
从零学习node.js之利用express搭建简易论坛(七)
2017/02/25 Javascript
jQuery插件zTree实现的多选树效果示例
2017/03/08 Javascript
详解vue mint-ui源码解析之loadmore组件
2017/10/11 Javascript
vue中实现图片压缩 file文件的方法
2020/05/28 Javascript
Vue时间轴 vue-light-timeline的用法说明
2020/10/29 Javascript
[02:17]2016国际邀请赛中国区预选赛VG战队领队采访
2016/06/26 DOTA
Python 实现 贪吃蛇大作战 代码分享
2016/09/07 Python
pandas DataFrame 根据多列的值做判断,生成新的列值实例
2018/05/18 Python
详解python实现识别手写MNIST数字集的程序
2018/08/03 Python
python获取交互式ssh shell的方法
2019/02/14 Python
Python嵌套函数,作用域与偏函数用法实例分析
2019/12/26 Python
python3跳出一个循环的实例操作
2020/08/18 Python
深入浅出CSS3 background-clip,background-origin和border-image教程
2011/01/27 HTML / CSS
CSS3中31种选择器使用方法教程
2013/12/05 HTML / CSS
Dower & Hall官网:英国小众轻奢珠宝品牌
2019/01/31 全球购物
上课迟到检讨书
2014/02/19 职场文书
青年安全生产示范岗事迹材料
2014/05/04 职场文书
职务任命书范本
2014/06/05 职场文书
公司周年庆典标语
2014/10/07 职场文书
学校党委干部个人对照检查材料思想汇报
2014/10/09 职场文书
董事长岗位职责
2015/02/13 职场文书
2015重阳节座谈会主持词
2015/07/30 职场文书
省级三好学生主要事迹材料
2015/11/03 职场文书
MySQL查看表和清空表的常用命令总结
2021/05/26 MySQL
redis lua限流算法实现示例
2022/07/15 Redis
服务器nginx权限被拒绝解决案例
2022/09/23 Servers