python 连接各类主流数据库的实例代码

本篇博文主要介绍Python连接各种数据库的方法及简单使用

包括关系数据库:sqlite,mysql,mssql

非关系数据库:MongoDB,Redis

代码写的比较清楚,直接上代码

1.连接sqlite

# coding=utf-8
# http://www.runoob.com/sqlite/sqlite-python.html
import sqlite3
import traceback

try:
 # 如果表不存在,就创建
 with sqlite3.connect('test.db') as conn:

  print("Opened database successfully")

  # 删除表
  conn.execute("DROP TABLE IF EXISTS COMPANY")

  # 创建表
  sql = """
     CREATE TABLE IF NOT EXISTS COMPANY
    (ID INTEGER PRIMARY KEY  AUTOINCREMENT,
    NAME   TEXT NOT NULL,
    AGE   INT  NOT NULL,
    ADDRESS  CHAR(50),
    SALARY   REAL);
  """
  conn.execute(sql)

  print("create table successfully")

  # 添加数据
  conn.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES (?, ?, ?, ? )",
       [('Paul', 32, 'California', 20000.00),
       ('Allen', 25, 'Texas', 15000.00),
       ('Teddy', 23, 'Norway', 20000.00),
       ('Mark', 25, 'Rich-Mond ', 65000.00),
       ('David', 27, 'Texas', 85000.00),
       ('Kim', 22, 'South-Hall', 45000.00),
       ('James', 24, 'Houston', 10000.00)])
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ( 'Paul', 32, 'California', 20000.00 )")
  #
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ('Allen', 25, 'Texas', 15000.00 )")
  #
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ('Teddy', 23, 'Norway', 20000.00 )")
  #
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 )")
  #
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ( 'David', 27, 'Texas', 85000.00 )");
  #
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ( 'Kim', 22, 'South-Hall', 45000.00 )")
  #
  # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
  # VALUES ( 'James', 24, 'Houston', 10000.00 )")

  # 提交,否则重新运行程序时,表中无数据
  conn.commit()
  print("insert successfully")

  # 查询表
  sql = """
   select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
   """

  result = conn.execute(sql)

  for row in result:
   print("-" * 50) # 输出50个-,作为分界线
   print("%-10s %s" % ("id", row[0])) # 字段名固定10位宽度,并且左对齐
   print("%-10s %s" % ("name", row[1]))
   print("%-10s %s" % ("age", row[2]))
   print("%-10s %s" % ("address", row[3]))
   print("%-10s %.2f" % ("salary", row[4]))
   # or
   # print('{:10s} {:.2f}'.format("salary", row[4]))

except sqlite3.Error as e:
 print("sqlite3 Error:", e)
 traceback.print_exc()

2.连接mysql

2.1使用mysqldb库中的_mysql

#! /usr/bin/env python2.7
# coding=utf-8
# Created by xiaosanyu at 16/5/30

# mysqldb 只支持python2.7
# http://mysql-python.sourceforge.net/

import MySQLdb
from contextlib import closing
import traceback

try:
 # 获取一个数据库连接
 with closing(MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', port=3306,charset='utf8')) as conn:
  print("connect database successfully")
  with closing(conn.cursor()) as cur:
   # 删除表
   cur.execute("DROP TABLE IF EXISTS COMPANY")
   # 创建表
   sql = """
      CREATE TABLE IF NOT EXISTS COMPANY
     (ID INTEGER PRIMARY KEY NOT NULL auto_increment,
     NAME   TEXT NOT NULL,
     AGE   INT  NOT NULL,
     ADDRESS  CHAR(50),
     SALARY   REAL);
   """
   cur.execute(sql)

   print("create table successfully")

   # 添加数据
   # 在一个conn.execute里面里面执行多个sql语句是非法的
   cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
       [('Paul', 32, 'California', 20000.00),
        ('Allen', 25, 'Texas', 15000.00),
        ('Teddy', 23, 'Norway', 20000.00),
        ('Mark', 25, 'Rich-Mond ', 65000.00),
        ('David', 27, 'Texas', 85000.00),
        ('Kim', 22, 'South-Hall', 45000.00),
        ('James', 24, 'Houston', 10000.00)])

   # 提交,否则重新运行程序时,表中无数据
   conn.commit()
   print("insert successfully")

   # 查询表
   sql = """
    select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
    """

   cur.execute(sql)

   for row in cur.fetchall():
    print("-" * 50) # 输出50个-,作为分界线
    print("%-10s %s" % ("id", row[0])) # 字段名固定10位宽度,并且左对齐
    print("%-10s %s" % ("name", row[1]))
    print("%-10s %s" % ("age", row[2]))
    print("%-10s %s" % ("address", row[3]))
    print("%-10s %s" % ("salary", row[4]))

except MySQLdb.Error as e:
 print("Mysql Error:", e)
 traceback.print_exc() # 打印错误栈信息

2.2 使用MySQLdb

#! /usr/bin/env python2.7
# coding=utf-8
# Created by xiaosanyu at 16/5/30

# mysqldb 只支持python2.7
# http://mysql-python.sourceforge.net/

import MySQLdb
from contextlib import closing
import traceback

try:
 # 获取一个数据库连接
 with closing(MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', port=3306,charset='utf8')) as conn:
  print("connect database successfully")
  with closing(conn.cursor()) as cur:
   # 删除表
   cur.execute("DROP TABLE IF EXISTS COMPANY")
   # 创建表
   sql = """
      CREATE TABLE IF NOT EXISTS COMPANY
     (ID INTEGER PRIMARY KEY NOT NULL auto_increment,
     NAME   TEXT NOT NULL,
     AGE   INT  NOT NULL,
     ADDRESS  CHAR(50),
     SALARY   REAL);
   """
   cur.execute(sql)

   print("create table successfully")

   # 添加数据
   # 在一个conn.execute里面里面执行多个sql语句是非法的
   cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
       [('Paul', 32, 'California', 20000.00),
        ('Allen', 25, 'Texas', 15000.00),
        ('Teddy', 23, 'Norway', 20000.00),
        ('Mark', 25, 'Rich-Mond ', 65000.00),
        ('David', 27, 'Texas', 85000.00),
        ('Kim', 22, 'South-Hall', 45000.00),
        ('James', 24, 'Houston', 10000.00)])

   # 提交,否则重新运行程序时,表中无数据
   conn.commit()
   print("insert successfully")

   # 查询表
   sql = """
    select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
    """

   cur.execute(sql)

   for row in cur.fetchall():
    print("-" * 50) # 输出50个-,作为分界线
    print("%-10s %s" % ("id", row[0])) # 字段名固定10位宽度,并且左对齐
    print("%-10s %s" % ("name", row[1]))
    print("%-10s %s" % ("age", row[2]))
    print("%-10s %s" % ("address", row[3]))
    print("%-10s %s" % ("salary", row[4]))

except MySQLdb.Error as e:
 print("Mysql Error:", e)
 traceback.print_exc() # 打印错误栈信息

2.3使用pymysql

2.1和2.2节使用MySQLdb,不支持Python3.x

pymysql对Python2.x和Python3.x的支持都比较好

# Created by xiaosanyu at 16/5/30
# coding=utf-8

# https://github.com/PyMySQL/PyMySQL/
import pymysql
from contextlib import closing
import traceback

try:
 # 获取一个数据库连接,with关键字 表示退出时,conn自动关闭
 # with 嵌套上一层的with 要使用closing()
 with closing(pymysql.connect(host='localhost', user='root', passwd='root', db='test', port=3306,
         charset='utf8')) as conn:

  print("connect database successfully")

  # 获取游标,with关键字 表示退出时,cur自动关闭
  with conn.cursor() as cur:
   # 删除表
   cur.execute("DROP TABLE IF EXISTS COMPANY")
   # 创建表
   sql = """
      CREATE TABLE IF NOT EXISTS COMPANY
     (ID INTEGER PRIMARY KEY NOT NULL auto_increment,
     NAME   TEXT NOT NULL,
     AGE   INT  NOT NULL,
     ADDRESS  CHAR(50),
     SALARY   REAL);
   """
   cur.execute(sql)

   print("create table successfully")

   # 添加数据
   # 在一个conn.execute里面里面执行多个sql语句是非法的
   cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
       [('Paul', 32, 'California', 20000.00),
        ('Allen', 25, 'Texas', 15000.00),
        ('Teddy', 23, 'Norway', 20000.00),
        ('Mark', 25, 'Rich-Mond ', 65000.00),
        ('David', 27, 'Texas', 85000.00),
        ('Kim', 22, 'South-Hall', 45000.00),
        ('James', 24, 'Houston', 10000.00)])

   # 提交,否则重新运行程序时,表中无数据
   conn.commit()
   print("insert successfully")

   # 查询表
   sql = """
    select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
    """

   cur.execute(sql)

   for row in cur.fetchall():
    print("-" * 50) # 输出50个-,作为分界线
    print("%-10s %s" % ("id", row[0])) # 字段名固定10位宽度,并且左对齐
    print("%-10s %s" % ("name", row[1]))
    print("%-10s %s" % ("age", row[2]))
    print("%-10s %s" % ("address", row[3]))
    print("%-10s %s" % ("salary", row[4]))
except pymysql.Error as e:
 print("Mysql Error:", e)
 traceback.print_exc()

3.连接mssql

# Created by xiaosanyu at 16/5/30

# http://www.pymssql.org/en/latest/
import pymssql
from contextlib import closing

try:
 # 先要保证数据库中有test数据库
 # 获取一个数据库连接,with关键字 表示退出时,conn自动关闭
 # with 嵌套上一层的with 要使用closing()
 with closing(pymssql.connect(host='192.168.100.114', user='sa', password='sa12345', database='test', port=1433,
         charset='utf8')) as conn:

  print("connect database successfully")

  # 获取游标,with关键字 表示退出时,cur自动关闭
  with conn.cursor() as cur:
   # 删除表
   cur.execute(
     '''if exists (select 1 from sys.objects where name='COMPANY' and type='U') drop table COMPANY''')
   # 创建表
   sql = """
      CREATE TABLE COMPANY
     (ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL ,
     NAME   TEXT NOT NULL,
     AGE   INT  NOT NULL,
     ADDRESS  CHAR(50),
     SALARY   REAL);
   """
   cur.execute(sql)

   print("create table successfully")

   # 添加数据
   # 在一个conn.execute里面里面执行多个sql语句是非法的
   cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
       [('Paul', 32, 'California', 20000.00),
        ('Allen', 25, 'Texas', 15000.00),
        ('Teddy', 23, 'Norway', 20000.00),
        ('Mark', 25, 'Rich-Mond', 65000.00),
        ('David', 27, 'Texas', 85000.00),
        ('Kim', 22, 'South-Hall', 45000.00),
        ('James', 24, 'Houston', 10000.00)])

   # 提交,否则重新运行程序时,表中无数据
   conn.commit()
   print("insert successfully")

   # 查询表
   sql = """
    select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
    """

   cur.execute(sql)

   for row in cur.fetchall():
    print("-" * 50) # 输出50个-,作为分界线
    print("%-10s %s" % ("id", row[0])) # 字段名固定10位宽度,并且左对齐
    print("%-10s %s" % ("name", row[1]))
    print("%-10s %s" % ("age", row[2]))
    print("%-10s %s" % ("address", row[3]))
    print("%-10s %s" % ("salary", row[4]))
except pymssql.Error as e:
 print("mssql Error:", e)
 # traceback.print_exc()

4.连接MongoDB

# Created by xiaosanyu at 16/5/30

# https://docs.mongodb.com/ecosystem/drivers/python/
# https://pypi.python.org/pypi/pymongo/

import pymongo
from pymongo.mongo_client import MongoClient
import pymongo.errors
import traceback

try:
 # 连接到 mongodb 服务
 mongoClient = MongoClient('localhost', 27017)
 # 连接到数据库
 mongoDatabase = mongoClient.test
 print("connect database successfully")

 # 获取集合
 mongoCollection = mongoDatabase.COMPANY

 # 移除所有数据
 mongoCollection.remove()

 # 添加数据
 mongoCollection.insert_many([{"Name": "Paul", "Age": "32", "Address": "California", "Salary": "20000.00"},
         {"Name": "Allen", "Age": "25", "Address": "Texas", "Salary": "15000.00"},
         {"Name": "Teddy", "Age": "23", "Address": "Norway", "Salary": "20000.00"},
         {"Name": "Mark", "Age": "25", "Address": "Rich-Mond", "Salary": "65000.00"},
         {"Name": "David", "Age": "27", "Address": "Texas", "Salary": "85000.00"},
         {"Name": "Kim", "Age": "22", "Address": "South-Hall", "Salary": "45000.00"},
         {"Name": "James", "Age": "24", "Address": "Houston", "Salary": "10000.00"}, ])

 #获取集合中的值
 for row in mongoCollection.find():
  print("-" * 50) # 输出50个-,作为分界线
  print("%-10s %s" % ("_id", row['_id'])) # 字段名固定10位宽度,并且左对齐
  print("%-10s %s" % ("name", row['Name']))
  print("%-10s %s" % ("age", row['Age']))
  print("%-10s %s" % ("address", row['Address']))
  print("%-10s %s" % ("salary", row['Salary']))

 print('\n\n\n')
 # 使id自增
 mongoCollection.remove()
 # 创建计数表
 mongoDatabase.counters.save({"_id": "people_id", "sequence_value": 0})
 # 创建存储过程
 mongoDatabase.system_js.getSequenceValue = '''function getSequenceValue(sequenceName){
   var sequenceDocument = db.counters.findAndModify({
    query: {_id: sequenceName},
    update: {$inc:{sequence_value: 1}},
    new:true
   });
   return sequenceDocument.sequence_value;
  }'''
 mongoCollection.insert_many(
   [{"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Paul", "Age": "32",
    "Address": "California", "Salary": "20000.00"},
    {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Allen", "Age": "25",
    "Address": "Texas", "Salary": "15000.00"},
    {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Teddy", "Age": "23",
    "Address": "Norway", "Salary": "20000.00"},
    {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Mark", "Age": "25",
    "Address": "Rich-Mond", "Salary": "65000.00"},
    {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "David", "Age": "27",
    "Address": "Texas", "Salary": "85000.00"},
    {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Kim", "Age": "22",
    "Address": "South-Hall", "Salary": "45000.00"},
    {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "James", "Age": "24",
    "Address": "Houston", "Salary": "10000.00"}, ])

 for row in mongoCollection.find():
  print("-" * 50) # 输出50个-,作为分界线
  print("%-10s %s" % ("_id", int(row['_id']))) # 字段名固定10位宽度,并且左对齐
  print("%-10s %s" % ("name", row['Name']))
  print("%-10s %s" % ("age", row['Age']))
  print("%-10s %s" % ("address", row['Address']))
  print("%-10s %s" % ("salary", row['Salary']))
except pymongo.errors.PyMongoError as e:
 print("mongo Error:", e)
 traceback.print_exc()

5.连接Redis

5.1使用redis

# coding=utf-8
# Created by xiaosanyu at 16/5/31

# https://pypi.python.org/pypi/redis/2.10.5
# http://redis-py.readthedocs.io/en/latest/#
import redis

r = redis.Redis(host='localhost', port=6379, db=0, password="12345")
print("connect", r.ping())

# 看信息
info = r.info()
# or 查看部分信息
# info = r.info("Server")

# 输出信息
items = info.items()
for i, (key, value) in enumerate(items):
 print("item %s----%s:%s" % (i, key, value))

# 删除键和对应的值
r.delete("company")

# 可以一次性push一条或多条数据
r.rpush("company", {"id": 1, "Name": "Paul", "Age": "32", "Address": "California", "Salary": "20000.00"},
  {"id": 2, "Name": "Allen", "Age": "25", "Address": "Texas", "Salary": "15000.00"},
  {"id": 3, "Name": "Teddy", "Age": "23", "Address": "Norway", "Salary": "20000.00"})
r.rpush("company", {"id": 4, "Name": "Mark", "Age": "25", "Address": "Rich-Mond", "Salary": "65000.00"})
r.rpush("company", {"id": 5, "Name": "David", "Age": "27", "Address": "Texas", "Salary": "85000.00"})
r.rpush("company", {"id": 6, "Name": "Kim", "Age": "22", "Address": "South-Hall", "Salary": "45000.00"})
r.rpush("company", {"id": 7, "Name": "James", "Age": "24", "Address": "Houston", "Salary": "10000.00"})

# eval用来将dict格式的字符串转换成dict
for row in map(lambda x: eval(x), r.lrange("company", 0, r.llen("company"))):
 print("-" * 50) # 输出50个-,作为分界线
 print("%-10s %s" % ("_id", row['id'])) # 字段名固定10位宽度,并且左对齐
 print("%-10s %s" % ("name", row['Name']))
 print("%-10s %s" % ("age", row['Age']))
 print("%-10s %s" % ("address", row['Address']))
 print("%-10s %s" % ("salary", row['Salary']))

# 关闭当前连接
# r.shutdown() #这个是关闭redis服务端

5.2使用pyredis

# Created by xiaosanyu at 16/5/30

# http://pyredis.readthedocs.io/en/latest/
import pyredis

r = pyredis.Client(host='localhost', port=6379, database=0, password="12345")
print("connect", r.ping().decode("utf-8"))

# 看信息

# info = r.execute("info").decode()
# or 查看部分信息
info = r.execute("info", "Server").decode()

# 输出信息
print(info)

# 删除键和对应的值
r.delete("company")

# 可以一次性push一条或多条数据
r.rpush("company", '''{"id": 1, "Name": "Paul", "Age": "32", "Address": "California", "Salary": "20000.00"}''',
  '''{"id": 2, "Name": "Allen", "Age": "25", "Address": "Texas", "Salary": "15000.00"}''',
  '''{"id": 3, "Name": "Teddy", "Age": "23", "Address": "Norway", "Salary": "20000.00"}''')
r.rpush("company", '''{"id": 4, "Name": "Mark", "Age": "25", "Address": "Rich-Mond", "Salary": "65000.00"}''')
r.rpush("company", '''{"id": 5, "Name": "David", "Age": "27", "Address": "Texas", "Salary": "85000.00"}''')
r.rpush("company", '''{"id": 6, "Name": "Kim", "Age": "22", "Address": "South-Hall", "Salary": "45000.00"}''')
r.rpush("company", '''{"id": 7, "Name": "James", "Age": "24", "Address": "Houston", "Salary": "10000.00"}''')

# eval用来将dict格式的字符串转换成dict
for row in map(lambda x: eval(x), r.lrange("company", 0, r.llen("company"))):
 print("-" * 50) # 输出50个-,作为分界线
 print("%-10s %s" % ("_id", row['id'])) # 字段名固定10位宽度,并且左对齐
 print("%-10s %s" % ("name", row['Name']))
 print("%-10s %s" % ("age", row['Age']))
 print("%-10s %s" % ("address", row['Address']))
 print("%-10s %s" % ("salary", row['Salary']))

# 关闭当前连接
r.close()

代码下载:python_connect_database

以上这篇python 连接各类主流数据库的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

您可能感兴趣的文章:

  • python连接数据库的方法
  • Python操作使用MySQL数据库的实例代码
  • python连接oracle数据库实例
  • 跟老齐学Python之通过Python连接数据库
(0)

相关推荐

  • python连接oracle数据库实例

    本文实例讲述了python连接oracle数据库的方法,分享给大家供大家参考.具体步骤如下: 一.首先下载驱动:(cx_Oracle) http://www.python.net/crew/atuining/cx_Oracle/ 不过要注意一下版本,根据你的情况加以选择. 二.安装: 首先配置oracle_home环境变量 执行那个exe安装程序就可以了,它会copy一个cx_Oracle.pyd到Libsite-packages目录下. 如果是linux,执行 复制代码 代码如下: pytho

  • 跟老齐学Python之通过Python连接数据库

    用Python来编写网站,必须要能够通过python操作数据库,所谓操作数据库,就是通过python实现对数据的连接,以及对记录.字段的各种操作.上一讲提到的那种操作方式,是看官直接通过交互模式来操作数据库. 安装python-MySQLdb 要想通过python来操作数据库,还需要在已经安装了mysql的基础上安装一个称之为mysqldb的库,它是一个接口程序,python通过它对mysql数据实现各种操作. 在编程中,会遇到很多类似的接口程序,通过接口程序对另外一个对象进行操作,比较简单.接

  • python连接数据库的方法

    MYSQL模块暂时还不支持python3.0以上的版本,由于我下载的python是3.0版本的,所以想要连接数据库只能利用其它的方法. Python3.x连接MySQL的方案有:oursql, PyMySQL, myconnpy 等,这里主要是安装pymysql 1.安装 pymysql安装:找到python文件夹pip程序的位置打开命令窗口: pip install pymysql3 2.使用 安装完毕后,数据库连接的具体步骤如下 引入 API 模块. 获取与数据库的连接. 执行SQL语句和存

  • Python操作使用MySQL数据库的实例代码

    Python 操作 MySQL 配置 win_64 Ubuntu14.04 Python3.x pip安装pymysql模块 直接使用pip安装 pip install pymysql win64上直接在cmd中执行 连接本地数据库 使用模块pymysql连接数据库 #!/usr/bin/python # coding=utf-8 import pymysql # 连接本地数据库 conn = pymysql.connect(host='localhost', port=3306, user='

  • python 连接各类主流数据库的实例代码

    本篇博文主要介绍Python连接各种数据库的方法及简单使用 包括关系数据库:sqlite,mysql,mssql 非关系数据库:MongoDB,Redis 代码写的比较清楚,直接上代码 1.连接sqlite # coding=utf-8 # http://www.runoob.com/sqlite/sqlite-python.html import sqlite3 import traceback try: # 如果表不存在,就创建 with sqlite3.connect('test.db')

  • python将字典内容存入mysql实例代码

    本文主要研究的是python将字典内容存入mysql,分享了实现代码,具体介绍如下. 1.背景 项目需要,用python实现了将字典内容存入本地的mysql数据库.比如说有个字典dic={"a":"b","c":"d"},存入数据库效果图如下: 2.代码 ''''' Insert items into database @author: hakuri ''' import MySQLdb def InsertData(Tabl

  • python连接读写操作redis的完整代码实例

    python读写操作redis数据库 redis有16个逻辑数据库(编号db0到db15),每个逻辑数据库数据是隔离的,默认db0.选择第n个逻辑数据库,命令select n ,python连接时可指定数据库编号(0~15). 为python安装支持库: pip install redis 连接redis 第一种方式,直连: import redis def redis_opt(): redis_conn = redis.Redis(host='127.0.0.1', port=6379, pa

  • PHP下 Mongodb 连接远程数据库的实例代码

    WINDOWS 下装MongoDB 先去官网下载  :https://www.mongodb.com/download-center#atlas 1.在mongodb的文件夹下创建 data.logs 文件夹 和mongo.conf 命令行命令! D:\mongodb\bin> mongod --dbpath D:\mongodb\data --logpath=D:\mongodb\logs\mongodb.log --logappend D:\mongodb\bin> mongod -dbp

  • python处理csv数据动态显示曲线实例代码

    本文研究的主要是python处理csv数据动态显示曲线,分享了实现代码,具体如下. 代码: # -*- coding: utf-8 -*- """ Spyder Editor This temporary script file is located here: C:\Users\user\.spyder2\.temp.py """ """ Show how to modify the coordinate form

  • Python编程scoketServer实现多线程同步实例代码

    本文研究的主要是Python编程scoketServer实现多线程同步的相关内容,具体介绍如下. 开发过程中,为了实现不同的客户端同一时刻只能有一个使用共同数据. 虽说用Python编写简单的网络程序很方便,但复杂一点的网络程序还是用现成的框架比较好.这样就可以专心事务逻辑,而不是套接字的各种细节.SocketServer模块简化了编写网络服务程序的任务.同时SocketServer模块也是Python标准库中很多服务器框架的基础. 网络服务类: SocketServer提供了4个基本的服务类:

  • Python并发之多进程的方法实例代码

    一,进程的理论基础 一个应用程序,归根结底是一堆代码,是静态的,而进程才是执行中的程序,在一个程序运行的时候会有多个进程并发执行. 进程和线程的区别: 进程是系统资源分配的基本单位. 一个进程内可以包含多个线程,属于一对多的关系,进程内的资源,被其内的线程共享 线程是进程运行的最小单位,如果说进程是完成一个功能,那么其线程就是完成这个功能的基本单位 进程间资源不共享,多进程切换资源开销,难度大,同一进程内的线程资源共享,多线程切换资源开销,难度小 进程与线程的共同点: 都是为了提高程序运行效率,

  • C# 操作 access 数据库的实例代码

    随笔: (1)   命名空间    using System.Data.OleDb; (2)   连接字符串 private staticstring connStr = @"Provider= Microsoft.Ace.OLEDB.12.0;Data Source = d:\login.accdb"; 注意: a.DataSource = 数据库存放的路径(这里数据库放到了D盘目录下)              b. 2003版本的Access数据库链接字符串: privatest

  • 使用Python做垃圾分类的原理及实例代码

    0 引言 纸巾再湿也是干垃圾?瓜子皮再干也是湿垃圾??最近大家都被垃圾分类折磨的不行,傻傻的你是否拎得清?

随机推荐