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遍历目录并批量更换文件名和目录名的方法
Sep 19 Python
Django基础之Model操作步骤(介绍)
May 27 Python
浅谈Python peewee 使用经验
Oct 20 Python
PyQt5主窗口动态加载Widget实例代码
Feb 07 Python
Python中一行和多行import模块问题
Apr 01 Python
Python异常处理操作实例详解
May 10 Python
对Python 数组的切片操作详解
Jul 02 Python
Flask框架各种常见装饰器示例
Jul 17 Python
pytorch: tensor类型的构建与相互转换实例
Jul 26 Python
Python 实现自动获取种子磁力链接方式
Jan 16 Python
解决tensorboard多个events文件显示紊乱的问题
Feb 15 Python
Python web如何在IIS发布应用过程解析
May 27 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
setcookie中Cannot modify header information-headers already sent by错误的解决方法详解
2013/05/08 PHP
php实现文件下载简单示例(代码实现文件下载)
2014/03/10 PHP
PHP数组操作类实例
2015/07/11 PHP
PHP上传图片、删除图片简单实例
2016/11/12 PHP
关于ThinkPhp 框架表单验证及ajax验证问题
2017/07/19 PHP
PHP实现权限管理功能示例
2017/09/22 PHP
php使用curl模拟浏览器表单上传文件或者图片的方法
2018/11/10 PHP
jquery 学习之二 属性 文本与值(text,val)
2010/11/25 Javascript
jQuery链式操作如何实现以及为什么要用链式操作
2013/01/17 Javascript
在线一元二次方程计算器实例(方程计算器在线计算)
2013/12/22 Javascript
jquery easyui combox一些实用的小方法
2013/12/25 Javascript
nodejs开发环境配置与使用
2014/11/17 NodeJs
node.js中的console.dir方法使用说明
2014/12/10 Javascript
JSON取值前判断
2014/12/23 Javascript
JavaScript中的逻辑判断符&&、||与!介绍
2014/12/31 Javascript
jQuery中:last-child选择器用法实例
2014/12/31 Javascript
webpack项目调试以及独立打包配置文件的方法
2018/02/28 Javascript
jQuery+Cookie实现切换皮肤功能【附源码下载】
2018/03/25 jQuery
详解vscode中vue代码颜色插件
2018/10/11 Javascript
JavaScript私有变量实例详解
2019/01/24 Javascript
Elementui表格组件+sortablejs实现行拖拽排序的示例代码
2019/08/28 Javascript
Layui多选只有最后一个值的解决方法
2019/09/02 Javascript
[06:33]DOTA2亚洲邀请赛小组赛第二日 TOP10精彩集锦
2015/01/31 DOTA
Python列出一个文件夹及其子目录的所有文件
2016/06/30 Python
Python代码实现http/https代理服务器的脚本
2019/08/12 Python
python+selenium select下拉选择框定位处理方法
2019/08/24 Python
python编程进阶之异常处理用法实例分析
2020/02/21 Python
python3 使用openpyxl将mysql数据写入xlsx的操作
2020/05/15 Python
HTML5 textarea高度自适应的两种方案
2020/04/08 HTML / CSS
美国现代家具网站:Design Within Reach
2018/07/19 全球购物
英国Iceland杂货店:网上食品购物
2020/12/16 全球购物
护理专科毕业推荐信
2013/11/10 职场文书
销售行政专员职责
2014/01/03 职场文书
网站客服岗位职责
2014/04/05 职场文书
Centos环境下Postgresql 安装配置及环境变量配置技巧
2021/05/18 PostgreSQL
Python实现滑雪小游戏
2021/09/25 Python