>  기사  >  백엔드 개발  >  Python의 일반적인 데이터베이스는 무엇입니까?

Python의 일반적인 데이터베이스는 무엇입니까?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼원래의
2019-06-12 11:11:539628검색

파이썬의 일반적인 데이터베이스는 무엇인가요? 데이터베이스는 크게 두 가지 범주로 나누어집니다. 첫 번째 범주에는 관계형 데이터베이스가 포함되고, 두 번째 범주에는 비관계형 데이터베이스가 포함됩니다. 다음은 이 두 가지 유형의 데이터베이스에 대한 관련 지식을 소개합니다.

관계형 데이터베이스 포함: sqlite, mysql, mssql

비관계형 데이터베이스: MongoDB, Redis

Python의 일반적인 데이터베이스는 무엇입니까?

1 SQLite에 연결

import sqlite3
import traceback
try:
    # 如果表不存在,就创建
    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', 20000.00),
                          ('Mark', 25, 'Rich-Mond ', 65000.00),
                          ('David', 27, 'Texas', 85000.00),
                          ('Kim', 22, 'South-Hall', 45000.00),
                          ('James', 24, 'Houston', 10000.00)])
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ( 'Paul', 32, 'California', 20000.00 )")
        #
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ('Allen', 25, 'Texas', 15000.00 )")
        #
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ('Teddy', 23, 'Norway', 20000.00 )")
        #
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 )")
        #
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ( 'David', 27, 'Texas', 85000.00 )");
        #
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ( 'Kim', 22, 'South-Hall', 45000.00 )")
        #
        # conn.execute("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\
        # VALUES ( 'James', 24, 'Houston', 10000.00 )")
        # 提交,否则重新运行程序时,表中无数据
        conn.commit()
        print("insert successfully")
        # 查询表
        sql = """
            select id,NAME,AGE,ADDRESS,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. 관련 추천: "

python 비디오 튜토리얼

2.2 MySQLdb 사용하기


2.1 mysqldb 라이브러리에서 _mysql 사용하기

import MySQLdb
from contextlib import closing
import traceback
try:
    # 获取一个数据库连接
    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,
                   NAME           TEXT    NOT NULL,
                   AGE            INT     NOT NULL,
                   ADDRESS        CHAR(50),
                   SALARY         REAL);
            """
            cur.execute(sql)
            print("create table successfully")
            # 添加数据
            # 在一个conn.execute里面里面执行多个sql语句是非法的
            cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
                            [('Paul', 32, 'California', 20000.00),
                             ('Allen', 25, 'Texas', 15000.00),
                             ('Teddy', 23, 'Norway', 20000.00),
                             ('Mark', 25, 'Rich-Mond ', 65000.00),
                             ('David', 27, 'Texas', 85000.00),
                             ('Kim', 22, 'South-Hall', 45000.00),
                             ('James', 24, 'Houston', 10000.00)])
            # 提交,否则重新运行程序时,表中无数据
            conn.commit()
            print("insert successfully")
            # 查询表
            sql = """
                select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
             """
            cur.execute(sql)
            for row in cur.fetchall():
                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 %s" % ("salary", row[4]))
except MySQLdb.Error as e:
    print("Mysql Error:", e)
    traceback.print_exc()  # 打印错误栈信息
2.2 MySQLdb 사용하기

import MySQLdb
from contextlib import closing
import traceback
try:
    # 获取一个数据库连接
    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,
                   NAME           TEXT    NOT NULL,
                   AGE            INT     NOT NULL,
                   ADDRESS        CHAR(50),
                   SALARY         REAL);
            """
            cur.execute(sql)
            print("create table successfully")
            # 添加数据
            # 在一个conn.execute里面里面执行多个sql语句是非法的
            cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
                            [('Paul', 32, 'California', 20000.00),
                             ('Allen', 25, 'Texas', 15000.00),
                             ('Teddy', 23, 'Norway', 20000.00),
                             ('Mark', 25, 'Rich-Mond ', 65000.00),
                             ('David', 27, 'Texas', 85000.00),
                             ('Kim', 22, 'South-Hall', 45000.00),
                             ('James', 24, 'Houston', 10000.00)])
            # 提交,否则重新运行程序时,表中无数据
            conn.commit()
            print("insert successfully")
            # 查询表
            sql = """
                select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
             """
            cur.execute(sql)
            for row in cur.fetchall():
                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 %s" % ("salary", row[4]))
except MySQLdb.Error as e:
    print("Mysql Error:", e)
    traceback.print_exc()  # 打印错误栈信息
2.3 pymysql 사용하기

섹션 2.1과 2.2에서는 MySQLdb를 사용합니다. Python 3에서는 지원되지 않습니다.

import pymysql
from contextlib import closing
import traceback
try:
    # 获取一个数据库连接,with关键字 表示退出时,conn自动关闭
    # with 嵌套上一层的with 要使用closing()
    with closing(pymysql.connect(host='localhost', user='root', passwd='root', db='test', port=3306,
                                 charset='utf8')) as conn:
        print("connect database successfully")
        # 获取游标,with关键字 表示退出时,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,
                   NAME           TEXT    NOT NULL,
                   AGE            INT     NOT NULL,
                   ADDRESS        CHAR(50),
                   SALARY         REAL);
            """
            cur.execute(sql)
            print("create table successfully")
            # 添加数据
            # 在一个conn.execute里面里面执行多个sql语句是非法的
            cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
                            [('Paul', 32, 'California', 20000.00),
                             ('Allen', 25, 'Texas', 15000.00),
                             ('Teddy', 23, 'Norway', 20000.00),
                             ('Mark', 25, 'Rich-Mond ', 65000.00),
                             ('David', 27, 'Texas', 85000.00),
                             ('Kim', 22, 'South-Hall', 45000.00),
                             ('James', 24, 'Houston', 10000.00)])
            # 提交,否则重新运行程序时,表中无数据
            conn.commit()
            print("insert successfully")
            # 查询表
            sql = """
                select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
             """
            cur.execute(sql)
            for row in cur.fetchall():
                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 %s" % ("salary", row[4]))
except pymysql.Error as e:
    print("Mysql Error:", e)
    traceback.print_exc()

5.2, pyredis

import pymssql
from contextlib import closing
try:
    # 先要保证数据库中有test数据库
    # 获取一个数据库连接,with关键字 表示退出时,conn自动关闭
    # with 嵌套上一层的with 要使用closing()
    with closing(pymssql.connect(host='192.168.100.114', user='sa', password='sa12345', database='test', port=1433,
                                 charset='utf8')) as conn:
        print("connect database successfully")
        # 获取游标,with关键字 表示退出时,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 ,
                   NAME           TEXT    NOT NULL,
                   AGE            INT     NOT NULL,
                   ADDRESS        CHAR(50),
                   SALARY         REAL);
            """
            cur.execute(sql)
            print("create table successfully")
            # 添加数据
            # 在一个conn.execute里面里面执行多个sql语句是非法的
            cur.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( %s, %s, %s, %s )",
                            [('Paul', 32, 'California', 20000.00),
                             ('Allen', 25, 'Texas', 15000.00),
                             ('Teddy', 23, 'Norway', 20000.00),
                             ('Mark', 25, 'Rich-Mond', 65000.00),
                             ('David', 27, 'Texas', 85000.00),
                             ('Kim', 22, 'South-Hall', 45000.00),
                             ('James', 24, 'Houston', 10000.00)])
            # 提交,否则重新运行程序时,表中无数据
            conn.commit()
            print("insert successfully")
            # 查询表
            sql = """
                select id,NAME,AGE,ADDRESS,SALARY FROM COMPANY
             """
            cur.execute(sql)
            for row in cur.fetchall():
                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 %s" % ("salary", row[4]))
except pymssql.Error as e:
    print("mssql Error:", e)
    # traceback.print_exc()
사용

위 내용은 Python의 일반적인 데이터베이스는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.