Python之数据库连接
Python之数据库连接
本文总结,常用Python连接各种数据源的配置,可用于脚本编写保存数据至数据库,以下实例仅供参考学习,欢迎共同学习。
import pymongo #连接数据库 client = pymongo.MongoClient('10.0.0.10') #连接指定数据库 db = client['commerce-db'] #指定goods 集合 result = db['goods'].find() ww = db['goods'].insert_one({'a':'qw'}) aa = db['test'].insert_many([{'a':'qw'},{'a':'qw'}]) # print(ww) #<pymongo.cursor.Cursor object at 0x0000000002F3A7F0> print(result) #<pymongo.cursor.Cursor object at 0x0000000002F3A7F0> for i in result: #需要遍历才能拿到每条document的信息 print(i)
2 连接redis数据库
import redis # 普通连接 conn = redis.Redis(host="10.0.0.10", port=6379,password="123456", decode_responses=True) conn.set("x1","hello",ex=5) # ex代表seconds,px代表ms val = conn.get("x1") print(val)
使用连接池进行连接
import redis # 连接池 pool = redis.ConnectionPool(host="10.0.0.10", port=6379,password="123456",max_connections=1024) conn = redis.Redis(connection_pool=pool) print(conn.get("x1"))
3 连 接mysql
python3中操作mysql数据需要安装一个第三方模块,pymysql,使用pip install pymysql安装即可,在python2中是MySQLdb模块,在python3中没有MySQLdb模块了,所以使用pymysql。
import pymysql def connect_mysql(): '''连接数据库方法''' #连接数据库 conn = pymysql.connect(host="10.0.0.10",port=3306,user="wei",passwd="123456",database="comme-db") #使用cursor()方法创建一个游标对象 cursor = conn.cursor() #使用execute()方法执行SQL语句 cursor.execute("SELECT * FROM HT_VIRTUAL_GIFT") #使用fetall()获取全部数据 data = cursor.fetchall() cursor.close() conn.close() #关闭游标和数据库的连接 return data for i in connect_mysql(): print(i)
3.1 mysql2.7连接2个mysql
import pymysql //连接 db1 = MySQLdb.connect(host=10.0.0.10, user=user, passwd=123456, db=commer-db, port=3306) db2 = MySQLdb.connect(host=10.0.0.20, user=user, passwd=123456, db=goods-db, port=3306) // 新增autocommit属性,设置自动提交 【不设置,会导致数据只能写到db1,且不显示报错】 db1.autocommit(1) db2.autocommit(1) //获取cursor对象 cursor = db1.cursor() cursor_build = db2.cursor() //操作数据库 cursor.execute(sql1) cursor_build.execute(sql2)
import pymysql from dbutils.pooled_db import PooledDB # 5表示最高5个连接 pool = PooledDB(pymysql, 5, host="10.0.0.10", user='root', password='123456', database='commer-db', port=3306, charset="utf8") conn = pool.connection() cur = conn.cursor() SQL = "SELECT * FROM scrapy_config" r = cur.execute(SQL) r = cur.fetchall() print(r) cur.close() conn.close()
import cx_Oracle conn = cx_Oracle.connect('commen-db', '123456', '127.0.0.1/commen-db', encoding='utf-8') if conn: print('orecle connect success')
import psycopg2 conn = psycopg2.connect(database='commen-db', host='10.0.0.10', user='postgres', password='123456', port=5432) if conn: print('postgresql connect success')
import pymssql conn = pymssql.connect(database='commen-db', host='10.0.0.10', user='wei', password='123456', port=1433) if conn: print('sqlserver connect success')
7 sqlalchemy连接数据库
from sqlalchemy import create_engine conn_str = 'oracle://wei:123456@10.0.0.10:1521/commen-db' engine = create_engine(conn_str) df.to_sql('tablename', engine, index=False, if_exists='append', dtype=type_dict)