Python 中连接MSSQL,MySQL,SQLite,Redis,ElasticSearch,Mongodb,PostgreSQL,Oracle,RabbitMQ
在Python中,可以使用各种库来连接和操作不同类型的数据库,如MSSQL, MySQL, SQLite, Redis, ElasticSearch, MongoDB, PostgreSQL 和 Oracle。以下是一些示例代码:
- 连接MSSQL:
import pymssql
conn = pymssql.connect(server='your_server', user='your_username', password='your_password', database='your_database')
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
conn.close()
- 连接MySQL:
import mysql.connector
conn = mysql.connector.connect(host='your_host', user='your_username', password='your_password', database='your_database')
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
conn.close()
- 连接SQLite:
import sqlite3
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
conn.close()
- 连接Redis:
import redis
r = redis.Redis(host='your_host', port=your_port, db=your_db)
value = r.get('your_key')
print(value)
- 连接ElasticSearch:
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts=['your_host'])
response = es.search(index='your_index', body={'query': {'match_all': {}}})
print(response)
- 连接MongoDB:
from pymongo import MongoClient
client = MongoClient('mongodb://your_username:your_password@your_host:your_port/your_database')
db = client['your_database']
collection = db['your_collection']
document = collection.find_one()
print(document)
- 连接PostgreSQL:
import psycopg2
conn = psycopg2.connect(dbname='your_dbname', user='your_user', password='your_pw', host='your_host', port='your_port')
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
conn.close()
- 连接Oracle:
import cx_Oracle
conn =
评论已关闭