python多对多关系如何将两个表连接成第三个表

时间:2015-08-02 00:13:33

标签: python sql many-to-many relationships

所以我试图在作者和书籍之间建立多对多的关系。我的作者表是author_id,author_first,author_last。对于我的书籍表,我有book_id和book_title。我写的第三个表有book_id和author_id。我正在处理我的python代码,我有两个类main和一个数据库。对于我的b_command,我试图让我的结果如下: 输入书名:我喜欢书 输入作者ID:1 输入作者ID:2 但我似乎无法想到如何在那里添加作者ID。 这是我的主要方法的代码:

import pymysql
from project2database import *

db = database("project2")

done = False

def dashes(size=80,char='-'):
    print(char*size)

def commands():
    print("Commands are a(add an author), la(list the authors), b(enter a book with the author id), lb(list of books), q(quit)")

def a_command():
    #done = False
    print("Enter the name for an author. An empty first name ends the input")
    while not done:
        first= input("Enter the first name for an author: ")
        first = first.strip()
        if first == "":
            done = True
        else:
            last = input("Enter the last name for an author: ")
            last = last.strip()
            db.add_author(first,last)

def la_command():
    db.print_author()

def b_command():
    done = False
    print("Enter the name for a book and the Author id: ")
    while not done:
        title = input("Enter a book title: ")
        title = title.strip()
        if title=="":
            done = True
        else:
            db.add_book(title)





stop = False
commands()
while not stop:
    command = input("Enter your command --> ")
    command = command.strip().lower()
    if command == 'a':
        a_command()
    elif command == 'la':
        la_command()
    elif command == 'b':
        b_command()
    elif command == 'q':
        stop = True
    elif command == "":
        pass
    else:

这是我的数据库代码:

导入pymysql import sys

类数据库:

con = ""
name = ""
dbname = ""
last=0

def __init__(self,db_name): ## constructor
    try:
        self.con= pymysql.connect(host="localhost", user="root", passwd="", db=db_name)
    except pymysql.Error as e:
        print("Database Error [{:d}]: {:s}".format(e.args[0], e.args[1]))
        sys.exit(0)
    self.dbname = db_name

def close(self):   
    self.con.close()

def add_author(self,first,last):
    query = "insert into author(author_first,author_last) values ('{:s}','{:s}')".format(first,last)
    try:
        cur = self.con.cursor()
        cur.execute(query)
        self.last = cur.lastrowid
        self.con.commit()
        #print(query)
    except pymysql.Error as e:
        print("Database Error[{:d}]: {:s}".format(e.args[0], e.args[1]))

def print_author(self):
    print("The authors are: ")
    query = """
     select author_id,author_first,author_last from author
    """
    cur = self.con.cursor()
    cur.execute(query)
    row = cur.fetchone()

    while row is not None:
        print("{:d}->{:s},{:s}".format(row[0],row[1],row[2]))
        row = cur.fetchone()

def add_book(self,title)
    query = "insert into books(book_title) values ('{:s}')".format(title)
    try:
        cur = self.con.cursor()
        cur.execute(query)
        self.last = cur.lastrowid
        self.con.commit()
    except pymysql.Error as e:
        print("Database Error[{{:d}]: {:s}".format(e.args[0], e.args[1]))

1 个答案:

答案 0 :(得分:0)

您需要确保表格中的ID字段设置为AUTO INCREMENTIDENTITY

这意味着每次插入新记录时,数据库都会将增加的值(自上一次插入以来)分配给ID字段。

你不应该自己设置ID值,让RDBMS为你做。