• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python连接MySQL、MongoDB、Redis、memcache等数据库的方法

python 搞代码 4年前 (2022-01-08) 28次浏览 已收录 0个评论

这篇文章主要介绍了python连接操作MySQL、MongoDB、Redis、memcache等数据库的方法,大家可以参考使用

用Python写脚本也有一段时间了,经常操作数据库(MySQL),现在就整理下对各类数据库的操作,如后面有新的参数会补进来,慢慢完善。

一,python 操作 MySQL:详情见:
【apt-get install python-mysqldb】

代码如下:
#!/bin/env python
# -*- encoding: utf-8 -*-
#——————————————————————————-
# Purpose:     example for python_to_mysql
# Author:      zhoujy
# Created:     2013-06-14
# update:      2013-06-14
#——————————————————————————-
import MySQLdb
import os

#建立和数据库系统的连接,格式
#conn   = MySQLdb.connect(host=’localhost’,user=’root’,passwd=’123456′,db=’test’,port=3306,charset=’utf8′)

#指定配置文件,确定目录,或则写绝对路径
cwd = os.path.realpath(os.path.dirname(__file__))
db_conf = os.path.join(cwd, ‘db.conf’)
conn   = MySQLdb.connect(read_default_file=db_conf,host=’localhost’,db=’test’,port=3306,charset=’utf8′)

#要执行的sql语句
query  = ‘select id  from t1’

#获取操作游标
cursor = conn.cursor()

#执行SQL
cursor.execute(query)

#获取一条记录,每条记录做为一个元组返回,返回3,游标指到第2条记录。
result1 = cursor.fetchone()
for i in result1:
    print i
#返回影响的行数
    print cursor.rowcount

#获取指定数量记录,每条记录做为一个元组返回,返回1,2,游标从第2条记录开始,游标指到第4条记录。
result2 = cursor.fetchmany(2)
for i in result2:
   来源gao@dai!ma.com搞$代^码网 for ii in i:
        print ii

#获取所有记录,每条记录做为一个元组返回,返回3,4,7,6,游标从第4条记录开始到最后。
result3 = cursor.fetchall()
for i in result3:
    for ii in i:
        print ii

#获取所有记录,每条记录做为一个元组返回,返回3,4,7,6,游标从第1条记录开始
#重置游标位置,0为偏移量,mode=absolute | relative,默认为relative
cursor.scroll(0,mode=’absolute’)
result3 = cursor.fetchall()
for i in result3:
    for ii in i:
        print ii

#以下2种方法都可以把数据插入数据库:
#(one)
for i in range (10,20):
    query2 = ‘insert into t1 values(“%d”,now())’ %i
    cursor.execute(query2)
    #提交
    conn.rollback()
#(two)
rows = []
for i in range (10,20):
    rows.append(i)
query2 = ‘insert into t1 values(“%s”,now())’
#executemany 2个参数,第2个参数是变量。
cursor.executemany(query2,rows)
#提交
conn.commit()

#选择数据库
query3 = ‘select id from dba_hospital’
#重新选择数据库
conn.select_db(‘chushihua’)

cursor.execute(query3)

result4 = cursor.fetchall()
for i in result4:
    for ii in i:
        print ii
#不定义query,直接执行:
cursor.execute(“set session binlog_format=’mixed'”)

#关闭游标,释放资源
cursor.close()

”’
+——+———————+
| id   | modifyT             |
+——+———————+
|    3 | 2010-01-01 00:00:00 |
|    1 | 2010-01-01 00:00:00 |
|    2 | 2010-01-01 00:00:00 |
|    3 | 2010-01-01 00:00:00 |
|    4 | 2013-06-04 17:04:54 |
|    7 | 2013-06-04 17:05:36 |
|    6 | 2013-06-04 17:05:17 |
+——+———————+

”’

以上就是python连接MySQL、MongoDB、Redis、memcache等数据库的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python连接MySQL、MongoDB、Redis、memcache等数据库的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址