当前位置: 首页 > 工具软件 > c2sqlite > 使用案例 >

Python SQLite3 join示例

濮阳功
2023-12-01
import sqlite3

from sqlite3 import Error


def sql_connection():
    try:

        con = sqlite3.connect(':memory:')

        return con

    except Error:

        print(Error)


def sql_table(con):
    cursorObj = con.cursor()

    cursorObj.execute(
        '''create table a_table (
  id int primary key not null,
  c2 int not null,
  c3 int not null
);''')

    con.commit()

    cursorObj.execute('''create table b_table (
  pid int not null references a_table,
  c2 int not null
);''')
    con.commit()
    cursorObj.execute('insert into a_table values (1, 2, 3);')
    con.commit()
    cursorObj.execute('insert into b_table values (1, 4);')
    con.commit()
    cursorObj.execute('insert into b_table values (1, 5);')

    con.commit()
    cursorObj.execute('select * from a_table;')

    rows = cursorObj.fetchall()

    for row in rows:
        print(row)

    cursorObj.execute('select * from b_table;')

    rows = cursorObj.fetchall()

    for row in rows:
        print(row)

    cursorObj.execute('select a.c2, a.c3, b.c2 from a_table a inner join b_table b on a.id=b.pid;')

    rows = cursorObj.fetchall()

    for row in rows:
        print(row)


con = sql_connection()

sql_table(con)

(1, 2, 3)
(1, 4)
(1, 5)
(2, 3, 4)
(2, 3, 5)

 类似资料: