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

python 连接各类主流数据库的实例代码,第1张

概述本篇博文主要介绍Python连接各种数据库的方法及简单使用包括关系数据库:sqlite,mysql,mssql

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

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

非关系数据库:MongoDB,Redis

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

1.连接sqlite

# Coding=utf-8# http://www.runoob.com/sqlite/sqlite-python.HTMLimport sqlite3import tracebacktry: # 如果表不存在,就创建 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',('Mark','Rich-Mond ',65000.00),('DavID',27,85000.00),('Kim',22,'South-Hall',45000.00),('James',24,'Houston',10000.00)])  # conn.execute("INSERT INTO COMPANY (name,SALARY)\  # VALUES ( 'Paul',20000.00 )")  #  # conn.execute("INSERT INTO COMPANY (name,SALARY)\  # VALUES ('Allen',15000.00 )")  #  # conn.execute("INSERT INTO COMPANY (name,SALARY)\  # VALUES ('Teddy',SALARY)\  # VALUES ( 'Mark',65000.00 )")  #  # conn.execute("INSERT INTO COMPANY (name,SALARY)\  # VALUES ( 'DavID',85000.00 )");  #  # conn.execute("INSERT INTO COMPANY (name,SALARY)\  # VALUES ( 'Kim',45000.00 )")  #  # conn.execute("INSERT INTO COMPANY (name,SALARY)\  # VALUES ( 'James',10000.00 )")  # 提交,否则重新运行程序时,表中无数据  conn.commit()  print("insert successfully")  # 查询表  sql = """   select ID,name,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 MysqLdbfrom contextlib import closingimport tracebacktry: # 获取一个数据库连接 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,SALARY   REAL);   """   cur.execute(sql)   print("create table successfully")   # 添加数据   # 在一个conn.execute里面里面执行多个SQL语句是非法的   cur.executemany("INSERT INTO COMPANY (name,SALARY) VALUES ( %s,%s,%s )",10000.00)])   # 提交,表中无数据   conn.commit()   print("insert successfully")   # 查询表   sql = """    select ID,SALARY FROM COMPANY    """   cur.execute(sql)   for row in cur.fetchall():    print("-" * 50) # 输出50个-,作为分界线    print("%-10s %s" % ("ID",并且左对齐    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 MysqLdbfrom contextlib import closingimport tracebacktry: # 获取一个数据库连接 with closing(MysqLdb.connect(host='localhost',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 pyMysqLfrom contextlib import closingimport tracebacktry: # 获取一个数据库连接,with关键字 表示退出时,conn自动关闭 # with 嵌套上一层的with 要使用closing() with closing(pyMysqL.connect(host='localhost',charset='utf8')) as conn:  print("connect database successfully")  # 获取游标,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,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 pymssqlfrom contextlib import closingtry: # 先要保证数据库中有test数据库 # 获取一个数据库连接,conn自动关闭 # with 嵌套上一层的with 要使用closing() with closing(pymssql.connect(host='192.168.100.114',user='sa',password='sa12345',database='test',port=1433,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,'Rich-Mond',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 pymongofrom pymongo.mongo_clIEnt import MongoClIEntimport pymongo.errorsimport tracebacktry: # 连接到 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",{"name": "Mark","Address": "Rich-Mond","Salary": "65000.00"},{"name": "DavID","Age": "27","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",{"_ID": mongoDatabase.eval("getSequenceValue('people_ID')"),"name": "Allen","name": "Teddy","name": "Mark","name": "DavID","name": "Kim","name": "James",]) for row in mongoCollection.find():  print("-" * 50) # 输出50个-,int(row['_ID']))) # 字段名固定10位宽度,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 redisr = 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,{"ID": 2,{"ID": 3,"Salary": "20000.00"})r.rpush("company",{"ID": 4,"Salary": "65000.00"})r.rpush("company",{"ID": 5,"Salary": "85000.00"})r.rpush("company",{"ID": 6,"Salary": "45000.00"})r.rpush("company",{"ID": 7,"Salary": "10000.00"})# eval用来将dict格式的字符串转换成dictfor row in map(lambda x: eval(x),r.lrange("company",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 pyredisr = pyredis.ClIEnt(host='localhost',database=0,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,"Salary": "20000.00"}''','''{"ID": 2,"Salary": "15000.00"}''','''{"ID": 3,"Salary": "20000.00"}''')r.rpush("company",'''{"ID": 4,"Salary": "65000.00"}''')r.rpush("company",'''{"ID": 5,"Salary": "85000.00"}''')r.rpush("company",'''{"ID": 6,"Salary": "45000.00"}''')r.rpush("company",'''{"ID": 7,"Salary": "10000.00"}''')# eval用来将dict格式的字符串转换成dictfor row in map(lambda x: eval(x),row['Salary']))# 关闭当前连接r.close()

代码下载:python_connect_database

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

您可能感兴趣的文章:python连接数据库的方法Python *** 作使用MySQL数据库的实例代码python连接oracle数据库实例跟老齐学Python之通过Python连接数据库 总结

以上是内存溢出为你收集整理的python 连接各类主流数据库的实例代码全部内容,希望文章能够帮你解决python 连接各类主流数据库的实例代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1200639.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存