zoukankan      html  css  js  c++  java
  • python 连接各数据库的代码

    转载自:测试派 http://testingpai.com/article/1596527686073

    1. MySQL  -- 已经实践

    pip install pymysql

    import pymysql

    # 第一步:连接到数据库
    con = pymysql.connect(host="localhost", # 数据库的地址
    user='root', # 登录数据库的账号
    password="xxxxx", # 登录数据库的密码
    port=3306, # 端口
    database='db_name', # 库名称
    )
    # 第二步:创建游标
    cur = con.cursor()
    # 第三步:执行对应的sql语句 方法:execute()
    sql = 'SELECT * FROM table_name;'
    cur.execute(sql)
    # 关闭游标
    cur.close()
    # 关闭连接
    conn.close()

    2.Oracle

    pip install cx_Oracle

    import cx_Oracle                   

    # 第一块 连接数据库 , 参数为'账号/密码/@ip:端口/库名'
    con=cx_Oracle.connect('user/password@host/databases')

    # 第二步 创建游标
    cur=con.cursor()
    # 第三步执行sql语句
    sql = 'SELECT * FROM table_name;'
    cur.execute(sql)
    # 关闭资源:游标、连接

    3. SQL Server

    pip install pymssql

    import pymssql

    # 第一步:连接到数据库
    con=pymssql.connect(host='localhost', # 数据库的地址
    user='root', # 登录数据库的账号
    password='xxxx', # 登录数据库的密码
    database='db_name') # 库名称

    # 第二步:创建游标
    cur = con.cursor()
    # 第三步:执行对应的sql语句 方法:execute()
    sql = 'SELECT * FROM table_name;'
    cur.execute(sql)


    4. PostgreSQL

    pip install psycopg2

    import psycopg2
    # 第一步:连接到数据库
    conn = psycopg2.connect(database="bd_name",
    user="root",
    password="xxxxxx",
    host="localhost",
    port="5432")

    # 第二步:创建游标
    cur = conn.cursor()
    # 第三步:执行对应的sql语句 方法:execute()
    sql = 'SELECT * FROM table_name;'
    cur.execute(sql)

    5. MongoDB

    pip install pymongo

    import pymongo

    # 第一步:建立连接
    client=pymongo.MongoClient("localhost", 27017)
    # 第二步:选取数据库
    db=client.test1
    # 第三步:选取集合
    stu = db.stu

    # 第四步:执行相关操作

    # 添加一条数据
    data1={name:'mongo',age:10}
    stu.insert_one(data1)
    # 获取一条数据
    s2=stu.find_one()

    6. Redis

    pip install redis

    import redis 

    st = redis.StrictRedis(
    host='localhost',# 服务器本机
    port=3306, # 端口:
    db=db_name, # 库:
    )
    # redis操作的命令,对应st对象的方法
    # 比如在数据库中创建一条键为test的数据,往里面添加3个元素
    st.lpush('test',11,22,33)
  • 相关阅读:
    排序算法的稳定性
    字符串处理常用函数
    判断两棵二叉树是否相等
    约瑟夫环
    自加++
    Linux 安装配置 Tomcat
    在 eclipse 中将 web 项目部署到 tomcat 服务器上
    PHP连接MySQL数据库
    logback
    Log4J
  • 原文地址:https://www.cnblogs.com/sue2015/p/15182877.html
Copyright © 2011-2022 走看看