国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python史上最全種類數(shù)據(jù)庫操作方法,你能想到的數(shù)據(jù)庫類型都在里面!甚至還有云數(shù)據(jù)庫!

這篇具有很好參考價值的文章主要介紹了Python史上最全種類數(shù)據(jù)庫操作方法,你能想到的數(shù)據(jù)庫類型都在里面!甚至還有云數(shù)據(jù)庫!。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

本文將詳細(xì)探討如何在Python中連接全種類數(shù)據(jù)庫以及實(shí)現(xiàn)相應(yīng)的CRUD(創(chuàng)建,讀取,更新,刪除)操作。我們將逐一解析連接MySQL,SQL Server,Oracle,PostgreSQL,MongoDB,SQLite,DB2,Redis,Cassandra,Microsoft Access,ElasticSearch,Neo4j,InfluxDB,Snowflake,Amazon DynamoDB,Microsoft Azure CosMos DB數(shù)據(jù)庫的方法,并演示相應(yīng)的CRUD操作。

MySQL

連接數(shù)據(jù)庫

Python可以使用mysql-connector-python庫連接MySQL數(shù)據(jù)庫:

import mysql.connector

conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')
print("Opened MySQL database successfully")
conn.close()

CRUD操作

接下來,我們將展示在MySQL中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')

cursor = conn.cursor()
cursor.execute("CREATE TABLE Employees (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT, ADDRESS CHAR(50), SALARY REAL)")
print("Table created successfully")

conn.close()

讀取(Retrieve)

conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')

cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("ADDRESS = ", row[2])
    print("SALARY = ", row[3])

conn.close()

更新(Update)

conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')

cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()

print("Total number of rows updated :", cursor.rowcount)

conn.close()

刪除(Delete)

conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')

cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()

print("Total number of rows deleted :", cursor.rowcount)

conn.close()

SQL Server

連接數(shù)據(jù)庫

Python可以使用pyodbc庫連接SQL Server數(shù)據(jù)庫:

import pyodbc

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')
print("Opened SQL Server database successfully")
conn.close()

CRUD操作

接下來,我們將展示在SQL Server中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')

cursor = conn.cursor()
cursor.execute("CREATE TABLE Employees (ID INT PRIMARY KEY NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT, ADDRESS CHAR(50), SALARY REAL)")
conn.commit()
print("Table created successfully")

conn.close()

讀?。≧etrieve)

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')

cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("ADDRESS = ", row[2])
    print("SALARY = ", row[3])

conn.close()

更新(Update)

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')

cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()

print("Total number of rows updated :", cursor.rowcount)

conn.close()

刪除(Delete)

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')

cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()

print("Total number of rows deleted :", cursor.rowcount)

conn.close()

Oracle

連接數(shù)據(jù)庫

Python可以使用cx_Oracle庫連接Oracle數(shù)據(jù)庫:

import cx_Oracle

dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database') 
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
print("Opened Oracle database successfully")
conn.close()

CRUD操作

接下來,我們將展示在Oracle中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database') 
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)

cursor = conn.cursor()
cursor.execute("CREATE TABLE Employees (ID NUMBER(10) NOT NULL PRIMARY KEY, NAME VARCHAR2(20) NOT NULL, AGE NUMBER(3), ADDRESS CHAR(50), SALARY NUMBER(10, 2))")
conn.commit()
print("Table created successfully")

conn.close()

讀?。≧etrieve)

dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database') 
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)

cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("ADDRESS = ", row[2])
    print("SALARY = ", row[3])

conn.close()

更新(Update)

dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database') 
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)

cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()

print("Total number of rows updated :", cursor.rowcount)

conn.close()

刪除(Delete)

dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database') 
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)

cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()

print("Total number of rows deleted :", cursor.rowcount)

conn.close()

PostgreSQL

連接數(shù)據(jù)庫

Python可以使用psycopg2庫連接PostgreSQL數(shù)據(jù)庫:

import psycopg2

conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")
print("Opened PostgreSQL database successfully")
conn.close()

CRUD操作

接下來,我們將展示在PostgreSQL中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")

cursor = conn.cursor()
cursor.execute('''CREATE TABLE Employees
      (ID INT PRIMARY KEY     NOT NULL,
      NAME           TEXT    NOT NULL,
      AGE            INT     NOT NULL,
      ADDRESS        CHAR(50),
      SALARY         REAL);''')
conn.commit()
print("Table created successfully")

conn.close()

讀?。≧etrieve)

conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")

cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("ADDRESS = ", row[2])
    print("SALARY = ", row[3])

conn.close()

更新(Update)

conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")

cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()

print("Total number of rows updated :", cursor.rowcount)

conn.close()

刪除(Delete)

conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")

cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()

print("Total number of rows deleted :", cursor.rowcount)

conn.close()

MongoDB

連接數(shù)據(jù)庫

Python可以使用pymongo庫連接MongoDB數(shù)據(jù)庫:

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
print("Opened MongoDB database successfully")
client.close()

CRUD操作

接下來,我們將展示在MongoDB中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

在MongoDB中,文檔的創(chuàng)建操作通常包含在插入操作中:

client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]

employees = db["Employees"]
employee = {"id": "1", "name": "John", "age": "30", "address": "New York", "salary": "1000.00"}

employees.insert_one(employee)
print("Document inserted successfully")

client.close()

讀?。≧etrieve)

client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]

employees = db["Employees"]
cursor = employees.find()
for document in cursor:
    print(document)

client.close()

更新(Update)

client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]

employees = db["Employees"]
query = { "id": "1" }
new_values = { "$set": { "salary": "25000.00" } }

employees.update_one(query, new_values)

print("Document updated successfully")

client.close()

刪除(Delete)

client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]

employees = db["Employees"]
query = { "id": "1" }

employees.delete_one(query)

print("Document deleted successfully")

client.close()

SQLite

連接數(shù)據(jù)庫

Python使用sqlite3庫連接SQLite數(shù)據(jù)庫:

import sqlite3

conn = sqlite3.connect('my_database.db')
print("Opened SQLite database successfully")
conn.close()

CRUD操作

接下來,我們將展示在SQLite中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

conn = sqlite3.connect('my_database.db')

cursor = conn.cursor()
cursor.execute('''CREATE TABLE Employees
      (ID INT PRIMARY KEY     NOT NULL,
      NAME           TEXT    NOT NULL,
      AGE            INT     NOT NULL,
      ADDRESS        CHAR(50),
      SALARY         REAL);''')
conn.commit()
print("Table created successfully")

conn.close()

讀?。≧etrieve)

conn = sqlite3.connect('my_database.db')

cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("ADDRESS = ", row[2])
    print("SALARY = ", row[3])

conn.close()

更新(Update)

conn = sqlite3.connect('my_database.db')

cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()

print("Total number of rows updated :", cursor.rowcount)

conn.close()

刪除(Delete)

conn = sqlite3.connect('my_database.db')

cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()

print("Total number of rows deleted :", cursor.rowcount)

conn.close()

DB2

連接數(shù)據(jù)庫

Python可以使用ibm_db庫連接DB2數(shù)據(jù)庫:

import ibm_db

dsn = (
    "DRIVER={{IBM DB2 ODBC DRIVER}};"
    "DATABASE=my_database;"
    "HOSTNAME=127.0.0.1;"
    "PORT=50000;"
    "PROTOCOL=TCPIP;"
    "UID=username;"
    "PWD=password;"
)
conn = ibm_db.connect(dsn, "", "")
print("Opened DB2 database successfully")
ibm_db.close(conn)

CRUD操作

接下來,我們將展示在DB2中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

conn = ibm_db.connect(dsn, "", "")

sql = '''CREATE TABLE Employees
      (ID INT PRIMARY KEY     NOT NULL,
      NAME           VARCHAR(20)    NOT NULL,
      AGE            INT     NOT NULL,
      ADDRESS        CHAR(50),
      SALARY         DECIMAL(9, 2));'''
stmt = ibm_db.exec_immediate(conn, sql)
print("Table created successfully")

ibm_db.close(conn)

讀取(Retrieve)

conn = ibm_db.connect(dsn, "", "")

sql = "SELECT id, name, address, salary from Employees"
stmt = ibm_db.exec_immediate(conn, sql)
while ibm_db.fetch_row(stmt):
    print("ID = ", ibm_db.result(stmt, "ID"))
    print("NAME = ", ibm_db.result(stmt, "NAME"))
    print("ADDRESS = ", ibm_db.result(stmt, "ADDRESS"))
    print("SALARY = ", ibm_db.result(stmt, "SALARY"))

ibm_db.close(conn)

更新(Update)

conn = ibm_db.connect(dsn, "", "")

sql = "UPDATE Employees set SALARY = 25000.00 where ID = 1"
stmt = ibm_db.exec_immediate(conn, sql)
ibm_db.commit(conn)

print("Total number of rows updated :", ibm_db.num_rows(stmt))

ibm_db.close(conn)

刪除(Delete)

conn = ibm_db.connect(dsn, "", "")

sql = "DELETE from Employees where ID = 1"
stmt = ibm_db.exec_immediate(conn, sql)
ibm_db.commit(conn)

print("Total number of rows deleted :", ibm_db.num_rows(stmt))

ibm_db.close(conn)

Microsoft Access

連接數(shù)據(jù)庫

Python可以使用pyodbc庫連接Microsoft Access數(shù)據(jù)庫:

import pyodbc

conn_str = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
    r'DBQ=path_to_your_access_file.accdb;'
)
conn = pyodbc.connect(conn_str)
print("Opened Access database successfully")
conn.close()

CRUD操作

接下來,我們將展示在Access中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

conn = pyodbc.connect(conn_str)

cursor = conn.cursor()
cursor.execute('''CREATE TABLE Employees
      (ID INT PRIMARY KEY     NOT NULL,
      NAME           TEXT    NOT NULL,
      AGE            INT     NOT NULL,
      ADDRESS        CHAR(50),
      SALARY         DECIMAL(9, 2));''')
conn.commit()
print("Table created successfully")

conn.close()

讀?。≧etrieve)

conn = pyodbc.connect(conn_str)

cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("ADDRESS = ", row[2])
    print("SALARY = ", row[3])

conn.close()

更新(Update)

conn = pyodbc.connect(conn_str)

cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()

print("Total number of rows updated :", cursor.rowcount)

conn.close()

刪除(Delete)

conn = pyodbc.connect(conn_str)

cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()

print("Total number of rows deleted :", cursor.rowcount)

conn.close()

Cassandra

連接數(shù)據(jù)庫

Python可以使用cassandra-driver庫連接Cassandra數(shù)據(jù)庫:

from cassandra.cluster import Cluster

cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')
print("Opened Cassandra database successfully")
cluster.shutdown()

CRUD操作

接下來,我們將展示在Cassandra中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')

session.execute("""
    CREATE TABLE Employees (
        id int PRIMARY KEY,
        name text,
        age int,
        address text,
        salary decimal
    )
""")
print("Table created successfully")

cluster.shutdown()

讀?。≧etrieve)

cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')

rows = session.execute('SELECT id, name, address, salary FROM Employees')
for row in rows:
    print("ID = ", row.id)
    print("NAME = ", row.name)
    print("ADDRESS = ", row.address)
    print("SALARY = ", row.salary)

cluster.shutdown()

更新(Update)

cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')

session.execute("UPDATE Employees SET salary = 25000.00 WHERE id = 1")
print("Row updated successfully")

cluster.shutdown()

刪除(Delete)

cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')

session.execute("DELETE FROM Employees WHERE id = 1")
print("Row deleted successfully")

cluster.shutdown()

Redis

連接數(shù)據(jù)庫

Python可以使用redis-py庫連接Redis數(shù)據(jù)庫:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
print("Opened Redis database successfully")

CRUD操作

接下來,我們將展示在Redis中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('employee:1:name', 'John')
r.set('employee:1:age', '30')
r.set('employee:1:address', 'New York')
r.set('employee:1:salary', '1000.00')

print("Keys created successfully")

讀?。≧etrieve)

r = redis.Redis(host='localhost', port=6379, db=0)

print("NAME = ", r.get('employee:1:name').decode('utf-8'))
print("AGE = ", r.get('employee:1:age').decode('utf-8'))
print("ADDRESS = ", r.get('employee:1:address').decode('utf-8'))
print("SALARY = ", r.get('employee:1:salary').decode('utf-8'))

更新(Update)

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('employee:1:salary', '25000.00')

print("Key updated successfully")

刪除(Delete)

r = redis.Redis(host='localhost', port=6379, db=0)

r.delete('employee:1:name', 'employee:1:age', 'employee:1:address', 'employee:1:salary')

print("Keys deleted successfully")

ElasticSearch

連接數(shù)據(jù)庫

Python可以使用elasticsearch庫連接ElasticSearch數(shù)據(jù)庫:

from elasticsearch import Elasticsearch

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
print("Opened ElasticSearch database successfully")

CRUD操作

接下來,我們將展示在ElasticSearch中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

employee = {
    'name': 'John',
    'age': 30,
    'address': 'New York',
    'salary': 1000.00
}
res = es.index(index='employees', doc_type='employee', id=1, body=employee)

print("Document created successfully")

讀?。≧etrieve)

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

res = es.get(index='employees', doc_type='employee', id=1)
print("Document details:")
for field, details in res['_source'].items():
    print(f"{field.upper()} = ", details)

更新(Update)

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

res = es.update(index='employees', doc_type='employee', id=1, body={
    'doc': {
        'salary': 25000.00
    }
})

print("Document updated successfully")

刪除(Delete)

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

res = es.delete(index='employees', doc_type='employee', id=1)

print("Document deleted successfully")

Neo4j

連接數(shù)據(jù)庫

Python可以使用neo4j庫連接Neo4j數(shù)據(jù)庫:

from neo4j import GraphDatabase

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
print("Opened Neo4j database successfully")
driver.close()

CRUD操作

接下來,我們將展示在Neo4j中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

with driver.session() as session:
    session.run("CREATE (:Employee {id: 1, name: 'John', age: 30, address: 'New York', salary: 1000.00})")

print("Node created successfully")

driver.close()

讀?。≧etrieve)

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

with driver.session() as session:
    result = session.run("MATCH (n:Employee) WHERE n.id = 1 RETURN n")
    for record in result:
        print("ID = ", record["n"]["id"])
        print("NAME = ", record["n"]["name"])
        print("ADDRESS = ", record["n"]["address"])
        print("SALARY = ", record["n"]["salary"])

driver.close()

更新(Update)

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

with driver.session() as session:
    session.run("MATCH (n:Employee) WHERE n.id = 1 SET n.salary = 25000.00")

print("Node updated successfully")

driver.close()

刪除(Delete)

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

with driver.session() as session:
    session.run("MATCH (n:Employee) WHERE n.id = 1 DETACH DELETE n")

print("Node deleted successfully")

driver.close()

InfluxDB

連接數(shù)據(jù)庫

Python可以使用InfluxDB-Python庫連接InfluxDB數(shù)據(jù)庫:

from influxdb import InfluxDBClient

client = InfluxDBClient(host='localhost', port=8086)
print("Opened InfluxDB database successfully")
client.close()

CRUD操作

接下來,我們將展示在InfluxDB中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

client = InfluxDBClient(host='localhost', port=8086)

json_body = [
    {
        "measurement": "employees",
        "tags": {
            "id": "1"
        },
        "fields": {
            "name": "John",
            "age": 30,
            "address": "New York",
            "salary": 1000.00
        }
    }
]

client.write_points(json_body)

print("Point created successfully")

client.close()

讀取(Retrieve)

client = InfluxDBClient(host='localhost', port=8086)

result = client.query('SELECT "name", "age", "address", "salary" FROM "employees"')

for point in result.get_points():
    print("ID = ", point['id'])
    print("NAME = ", point['name'])
    print("AGE = ", point['age'])
    print("ADDRESS = ", point['address'])
    print("SALARY = ", point['salary'])

client.close()

更新(Update)

InfluxDB的數(shù)據(jù)模型和其他數(shù)據(jù)庫不同,它沒有更新操作。但是你可以通過寫入一個相同的數(shù)據(jù)點(diǎn)(即具有相同的時間戳和標(biāo)簽)并改變字段值,實(shí)現(xiàn)類似更新操作的效果。

刪除(Delete)

同樣,InfluxDB也沒有提供刪除單個數(shù)據(jù)點(diǎn)的操作。然而,你可以刪除整個系列(即表)或者刪除某個時間段的數(shù)據(jù)。

client = InfluxDBClient(host='localhost', port=8086)

# 刪除整個系列
client.query('DROP SERIES FROM "employees"')

# 刪除某個時間段的數(shù)據(jù)
# client.query('DELETE FROM "employees" WHERE time < now() - 1d')

print("Series deleted successfully")

client.close()

Snowflake

連接數(shù)據(jù)庫

Python可以使用snowflake-connector-python庫連接Snowflake數(shù)據(jù)庫:

from snowflake.connector import connect

con = connect(
    user='username',
    password='password',
    account='account_url',
    warehouse='warehouse',
    database='database',
    schema='schema'
)
print("Opened Snowflake database successfully")
con.close()

CRUD操作

接下來,我們將展示在Snowflake中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

con = connect(
    user='username',
    password='password',
    account='account_url',
    warehouse='warehouse',
    database='database',
    schema='schema'
)

cur = con.cursor()
cur.execute("""
CREATE TABLE EMPLOYEES (
    ID INT,
    NAME STRING,
    AGE INT,
    ADDRESS STRING,
    SALARY FLOAT
)
""")

cur.execute("""
INSERT INTO EMPLOYEES (ID, NAME, AGE, ADDRESS, SALARY) VALUES
(1, 'John', 30, 'New York', 1000.00)
""")

print("Table created and row inserted successfully")

con.close()

讀?。≧etrieve)

con = connect(
    user='username',
    password='password',
    account='account_url',
    warehouse='warehouse',
    database='database',
    schema='schema'
)

cur = con.cursor()
cur.execute("SELECT * FROM EMPLOYEES WHERE ID = 1")

rows = cur.fetchall()

for row in rows:
    print("ID = ", row[0])
    print("NAME = ", row[1])
    print("AGE = ", row[2])
    print("ADDRESS = ", row[3])
    print("SALARY = ", row[4])

con.close()

更新(Update)

con = connect(
    user='username',
    password='password',
    account='account_url',
    warehouse='warehouse',
    database='database',
    schema='schema'
)

cur = con.cursor()
cur.execute("UPDATE EMPLOYEES SET SALARY = 25000.00 WHERE ID = 1")

print("Row updated successfully")

con.close()

刪除(Delete)

con = connect(
    user='username',
    password='password',
    account='account_url',
    warehouse='warehouse',
    database='database',
    schema='schema'
)

cur = con.cursor()
cur.execute("DELETE FROM EMPLOYEES WHERE ID = 1")

print("Row deleted successfully")

con.close()

Amazon DynamoDB

連接數(shù)據(jù)庫

Python可以使用boto3庫連接Amazon DynamoDB:

import boto3

dynamodb = boto3.resource('dynamodb', region_name='us-west-2',
                          aws_access_key_id='Your AWS Access Key',
                          aws_secret_access_key='Your AWS Secret Key')

print("Opened DynamoDB successfully")

CRUD操作

接下來,我們將展示在DynamoDB中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

table = dynamodb.create_table(
    TableName='Employees',
    KeySchema=[
        {
            'AttributeName': 'id',
            'KeyType': 'HASH'
        },
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'id',
            'AttributeType': 'N'
        },
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 5,
        'WriteCapacityUnits': 5
    }
)

table.put_item(
   Item={
        'id': 1,
        'name': 'John',
        'age': 30,
        'address': 'New York',
        'salary': 1000.00
    }
)

print("Table created and item inserted successfully")

讀取(Retrieve)

table = dynamodb.Table('Employees')

response = table.get_item(
   Key={
        'id': 1,
    }
)

item = response['Item']
print(item)

更新(Update)

table = dynamodb.Table('Employees')

table.update_item(
    Key={
        'id': 1,
    },
    UpdateExpression='SET salary = :val1',
    ExpressionAttributeValues={
        ':val1': 25000.00
    }
)

print("Item updated successfully")

刪除(Delete)

table = dynamodb.Table('Employees')

table.delete_item(
    Key={
        'id': 1,
    }
)

print("Item deleted successfully")

Microsoft Azure CosMos DB

連接數(shù)據(jù)庫

Python可以使用azure-cosmos庫連接Microsoft Azure CosMos DB:

from azure.cosmos import CosmosClient, PartitionKey, exceptions

url = 'Cosmos DB Account URL'
key = 'Cosmos DB Account Key'
client = CosmosClient(url, credential=key)

database_name = 'testDB'
database = client.get_database_client(database_name)

container_name = 'Employees'
container = database.get_container_client(container_name)

print("Opened CosMos DB successfully")

CRUD操作

接下來,我們將展示在CosMos DB中如何進(jìn)行基本的CRUD操作。

創(chuàng)建(Create)

database = client.create_database_if_not_exists(id=database_name)

container = database.create_container_if_not_exists(
    id=container_name, 
    partition_key=PartitionKey(path="/id"),
    offer_throughput=400
)

container.upsert_item({
    'id': '1',
    'name': 'John',
    'age': 30,
    'address': 'New York',
    'salary': 1000.00
})

print("Container created and item upserted successfully")

讀?。≧etrieve)

for item in container.read_all_items():
    print(item)

更新(Update)

for item in container.read_all_items():
    if item['id'] == '1':
        item['salary'] = 25000.00
        container.upsert_item(item)
        
print("Item updated successfully")

刪除(Delete)

for item in container.read_all_items():
    if item['id'] == '1':
        container.delete_item(item, partition_key='1')
        
print("Item deleted successfully")

如有幫助,請多關(guān)注
個人微信公眾號:【Python全視角】
TeahLead_KrisChang,10+年的互聯(lián)網(wǎng)和人工智能從業(yè)經(jīng)驗(yàn),10年+技術(shù)和業(yè)務(wù)團(tuán)隊(duì)管理經(jīng)驗(yàn),同濟(jì)軟件工程本科,復(fù)旦工程管理碩士,阿里云認(rèn)證云服務(wù)資深架構(gòu)師,上億營收AI產(chǎn)品業(yè)務(wù)負(fù)責(zé)人。文章來源地址http://www.zghlxwxcb.cn/news/detail-521494.html

到了這里,關(guān)于Python史上最全種類數(shù)據(jù)庫操作方法,你能想到的數(shù)據(jù)庫類型都在里面!甚至還有云數(shù)據(jù)庫!的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Python之?dāng)?shù)據(jù)庫操作(連接數(shù)據(jù)庫,增刪改查操作,易錯點(diǎn)理解)

    Python之?dāng)?shù)據(jù)庫操作(連接數(shù)據(jù)庫,增刪改查操作,易錯點(diǎn)理解)

    文章目錄 前言 一、Python之?dāng)?shù)據(jù)庫操作 二、 pymysql 安裝 三、pymysql 包引入 ?連接數(shù)據(jù)庫 創(chuàng)建游標(biāo) 執(zhí)行sql數(shù)據(jù) - 增刪改查 要獲取查詢結(jié)果數(shù)據(jù) 關(guān)閉游標(biāo),關(guān)閉數(shù)據(jù)庫連接 總結(jié) 記錄:Python操作數(shù)據(jù)庫的步驟,不容易理解的地方。 學(xué)習(xí)地址: python與各大數(shù)據(jù)庫的連接: http:/

    2023年04月16日
    瀏覽(57)
  • Python——數(shù)據(jù)庫操作

    Python——數(shù)據(jù)庫操作

    目錄 (1)安裝Flask-SQLAlchemy (2)使用Flask-SQLAlchemy操作數(shù)據(jù)庫 (3)連接數(shù)據(jù)庫 ??創(chuàng)建數(shù)據(jù)表 ?增加數(shù)據(jù) ?查詢數(shù)據(jù) ??更新數(shù)據(jù) ?刪除數(shù)據(jù) Flask-SQLAlchemy是Flask中用于操作關(guān)系型數(shù)據(jù)庫的擴(kuò)展包 ,該擴(kuò)展包內(nèi)部集成了SQLAlchemy,并簡化了在Flask程序中使用SQLAlchemy操作數(shù)據(jù)

    2024年02月04日
    瀏覽(27)
  • python操作數(shù)據(jù)庫

    首先安裝數(shù)據(jù)插件 數(shù)據(jù)庫的插入

    2024年02月13日
    瀏覽(26)
  • Python --數(shù)據(jù)庫操作

    目錄 1, mysql 1-1, mysql驅(qū)動 1-2, 連接mysql 1-3, 執(zhí)行sql語句 1-4, 數(shù)據(jù)表操作 1-4-1, 創(chuàng)建數(shù)據(jù)表 1-4-2, 查詢數(shù)據(jù)表 1-4-3, 修改數(shù)據(jù)表 1-4-4, 刪除數(shù)據(jù)表 1-5, 修改數(shù)據(jù)表內(nèi)容 1-5-1, 插入數(shù)據(jù) 1-5-2, 查詢數(shù)據(jù) 1-5-3, 獲取結(jié)果集 1-5-4, 更新數(shù)據(jù) 1-5-5, 刪除數(shù)據(jù) 1-6, 斷開mys

    2024年02月11日
    瀏覽(18)
  • Django操作MySQL數(shù)據(jù)庫的優(yōu)化方法

    Django 是一個很流行的 Web 框架,而 MySQL 是常用的關(guān)系型數(shù)據(jù)庫之一。在使用 Django 開發(fā) Web 應(yīng)用時,我們經(jīng)常需要使用 MySQL 存儲數(shù)據(jù),因此如何加速 MySQL 是我們需要關(guān)注的問題。本文將介紹一些方法來優(yōu)化 Django 中 MySQL 的性能。 使用適當(dāng)?shù)乃饕?索引是 MySQL 中提高查詢性能的

    2024年02月10日
    瀏覽(35)
  • Django的數(shù)據(jù)庫操作的游標(biāo)(cursor)方法

    在Django中,數(shù)據(jù)庫操作的游標(biāo)方法是一種直接與數(shù)據(jù)庫進(jìn)行交互的方式,它提供了更底層的數(shù)據(jù)庫訪問能力。通過游標(biāo)方法,你可以執(zhí)行原始的SQL查詢、事務(wù)處理以及處理大量數(shù)據(jù)等操作。 Django的數(shù)據(jù)庫游標(biāo)方法主要通過 connection 對象來執(zhí)行,其中 connection 對象表示與數(shù)據(jù)庫

    2024年02月13日
    瀏覽(21)
  • Python——操作MySQL數(shù)據(jù)庫

    Python——操作MySQL數(shù)據(jù)庫

    ??學(xué)習(xí)永無止境,記得每天學(xué)習(xí)新的知識??! 在很多業(yè)務(wù)場景中,我們或多或少都要對數(shù)據(jù)庫上的數(shù)據(jù)進(jìn)行的一系列操作, 包括讀取數(shù)據(jù)、寫數(shù)據(jù)、更新或修改數(shù)據(jù)、刪除數(shù)據(jù) 等。這些操作可以通過編寫SQL語句來實(shí)現(xiàn),也可以通過使用數(shù)據(jù)庫管理系統(tǒng)提供的API接口來實(shí)現(xiàn)。

    2024年02月09日
    瀏覽(47)
  • Python基礎(chǔ)之?dāng)?shù)據(jù)庫操作

    Python基礎(chǔ)之?dāng)?shù)據(jù)庫操作

    一、安裝第三方庫PyMySQL 1、在PyCharm中通過 【File】-【setting】-【Python Interpreter】搜索 PyMySQL進(jìn)行安裝 2、通過PyCharm中的 Terminal 命令行 輸入: pip install PyMySQL 注:通過pip安裝,可能會提示需要更新pip,這時可執(zhí)行:pip install --upgrade pip 進(jìn)行更新pip 二、mysql數(shù)據(jù)庫查詢(SELECT) 1、

    2024年01月24日
    瀏覽(29)
  • python與數(shù)據(jù)庫連接操作

    python與數(shù)據(jù)庫連接操作

    下載命令: pip install PyMySQL 一般我們會使用鏡像下載,這樣會比較快,比如清華鏡像: pip install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple 連接數(shù)據(jù)庫之前,我們需要知道自己需要連接數(shù)據(jù)庫的用戶名,密碼,數(shù)據(jù)庫名等信息 步驟: 連接connect() 創(chuàng)建cursor()對象 使用excute()執(zhí)行S

    2024年02月08日
    瀏覽(27)
  • Python 操作 MySQL 數(shù)據(jù)庫

    Python 標(biāo)準(zhǔn)數(shù)據(jù)庫接口為 Python DB-API,Python DB-API為開發(fā)人員提供了數(shù)據(jù)庫應(yīng)用編程接口。 Python 數(shù)據(jù)庫接口支持非常多的數(shù)據(jù)庫,你可以選擇適合你項(xiàng)目的數(shù)據(jù)庫: GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase 你可以訪問Python數(shù)據(jù)庫接口及API查看詳細(xì)的支

    2024年02月14日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包