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 相关文章推荐
pycharm 使用心得(五)断点调试
Jun 06 Python
利用python 更新ssh 远程代码 操作远程服务器的实现代码
Feb 08 Python
Python3.6实现连接mysql或mariadb的方法分析
May 18 Python
python numpy 一维数组转变为多维数组的实例
Jul 02 Python
详解如何从TensorFlow的mnist数据集导出手写体数字图片
Aug 05 Python
python Kmeans算法原理深入解析
Aug 23 Python
Python csv模块使用方法代码实例
Aug 29 Python
TensorFlow实现保存训练模型为pd文件并恢复
Feb 06 Python
Pytorch 高效使用GPU的操作
Jun 27 Python
浅谈Python3中print函数的换行
Aug 05 Python
pytorch 移动端部署之helloworld的使用
Oct 30 Python
详解python日志输出使用配置文件格式
Feb 10 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设计模式 Singleton(单例模式)
2011/06/26 PHP
php 调试利器debug_print_backtrace()
2012/07/23 PHP
php不使用插件导出excel的简单方法
2014/03/04 PHP
PHP实现的自定义数组排序函数与排序类示例
2016/11/18 PHP
PHP使Laravel为JSON REST API返回自定义错误的问题
2018/10/16 PHP
phpQuery采集网页实现代码实例
2020/04/02 PHP
防止网站内容被拷贝的一些方法与优缺点好处与坏处分析
2007/11/30 Javascript
jQuery获取css z-index在各种浏览器中的返回值
2010/09/15 Javascript
node.js 一个简单的页面输出实现代码
2012/03/07 Javascript
javascript获取作用在元素上面的样式属性代码
2012/09/20 Javascript
javaScript面向对象继承方法经典实现
2013/08/20 Javascript
javascript函数作用域学习示例(js作用域)
2014/01/13 Javascript
JavaScript中的数值范围介绍
2014/12/29 Javascript
深入理解JS中的Function.prototype.bind()方法
2016/10/11 Javascript
基于jQuery和CSS3实现APPLE TV海报视差效果
2017/06/16 jQuery
js编写简单的计时器功能
2017/07/15 Javascript
移动端Ionic App 资讯上下循环滚动的实现代码(跑马灯效果)
2017/08/29 Javascript
javascript数组常见操作方法实例总结【连接、添加、删除、去重、排序等】
2019/06/13 Javascript
vue配置文件实现代理v2版本的方法
2019/06/21 Javascript
vue实现Input输入框模糊查询方法
2021/01/29 Javascript
JavaScript实现一维数组转化为二维数组
2018/04/17 Python
Python中的函数作用域
2018/05/07 Python
python绘制多个子图的实例
2019/07/07 Python
导入tensorflow:ImportError: libcublas.so.9.0 报错
2020/01/06 Python
python实现飞船游戏的纵向移动
2020/04/24 Python
Python爬取网页信息的示例
2020/09/24 Python
Python中Pyspider爬虫框架的基本使用详解
2021/01/27 Python
pytorch Dataset,DataLoader产生自定义的训练数据案例
2021/03/03 Python
CSS3 实现的火焰动画
2020/12/07 HTML / CSS
迪卡侬英国官网:Decathlon英国
2017/04/08 全球购物
大学自我鉴定
2013/12/20 职场文书
学习标兵获奖感言
2014/02/20 职场文书
《自己去吧》教学反思
2016/02/16 职场文书
2016年安全生产先进个人事迹材料
2016/02/29 职场文书
Windows下redis下载、redis安装及使用教程
2021/06/02 Redis
Java 使用类型为Object的变量指向任意类型的对象
2022/04/13 Java/Android