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 相关文章推荐
pygame学习笔记(4):声音控制
Apr 15 Python
python使用PIL模块实现给图片打水印的方法
May 22 Python
简析Python的闭包和装饰器
Feb 26 Python
python多进程提取处理大量文本的关键词方法
Jun 05 Python
解决python报错MemoryError的问题
Jun 26 Python
python+mysql实现学生信息查询系统
Feb 21 Python
快速解决docker-py api版本不兼容的问题
Aug 30 Python
pycharm 2019 最新激活方式(pycharm破解、激活)
Sep 22 Python
Python 实现将大图切片成小图,将小图组合成大图的例子
Mar 14 Python
Python多线程thread及模块使用实例
Apr 28 Python
pytorch实现查看当前学习率
Jun 24 Python
2021年值得向Python开发者推荐的VS Code扩展插件
Jan 25 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
一首老MP3,致敬WAR3经典
2021/03/08 魔兽争霸
PHP求最大子序列和的算法实现
2011/06/24 PHP
PHP基础知识介绍
2013/09/17 PHP
PHP实现懒加载的方法
2015/03/07 PHP
Laravel jwt 多表(多用户端)验证隔离的实现
2019/12/18 PHP
javascript 数据类型转换(parseInt,parseFloat)
2010/07/20 Javascript
TinyMCE 新增本地图片上传功能
2010/11/05 Javascript
jquery提取元素里的纯文本不包含span等里的内容
2013/09/30 Javascript
javascript与cookie 的问题详解
2013/11/11 Javascript
jquery中的常见问题及快速解决方法小结
2016/06/14 Javascript
EditPlus中的正则表达式 实战(4)
2016/12/15 Javascript
JS获取短信验证码倒计时的实现代码
2017/05/22 Javascript
jQuery 实现批量提交表格多行数据的方法
2018/08/09 jQuery
手把手教你写一个微信小程序(推荐)
2018/10/17 Javascript
微信小程序实现搜索功能并跳转搜索结果页面
2019/05/18 Javascript
Vue 实现一个命令式弹窗组件功能
2019/09/25 Javascript
用Python脚本生成Android SALT扰码的方法
2013/09/18 Python
Python版微信红包分配算法
2015/05/04 Python
在Django的视图中使用数据库查询的方法
2015/07/16 Python
Python工程师面试题 与Python基础语法相关
2016/01/14 Python
Python3实现发送QQ邮件功能(附件)
2020/12/23 Python
Python常用模块os.path之文件及路径操作方法
2019/12/03 Python
python二维键值数组生成转json的例子
2019/12/06 Python
如何用python实现一个HTTP连接池
2021/01/14 Python
CSS3 中的@keyframes介绍
2014/09/02 HTML / CSS
Bowflex美国官方网站:高级家庭健身器材
2017/12/22 全球购物
党员教师一句话承诺
2014/05/30 职场文书
节约用电标语
2014/06/17 职场文书
单位工作证明
2014/10/07 职场文书
调解书格式范本
2015/05/20 职场文书
城南旧事电影观后感
2015/06/16 职场文书
2016年清明节寄语
2015/12/04 职场文书
500字作文之周记
2019/12/13 职场文书
python第三方网页解析器 lxml 扩展库与 xpath 的使用方法
2021/04/06 Python
MySQL中varchar和char类型的区别
2021/11/17 MySQL
Python语言中的数据类型-序列
2022/02/24 Python