【问题标题】:Update value in SQL table using SqlAlchemy in python?在 python 中使用 SqlAlchemy 更新 SQL 表中的值?
【发布时间】:2021-11-21 00:21:25
【问题描述】:
"""
Created on Tue Sep  7 14:06:54 2021

@author: hp
"""

"""BOOK DETAILS IN SQL USING PYTHON----python librarian"""
import pandas as pd
import pyodbc
from sqlalchemy import create_engine,update



"""SERVER="DESKTOP-JKOITFK\SQLEXPRESS"
DATABASE="newdatabase"
DRIVER="SQL SERVER NATIVE CLIENT 11.0"
USERNAME="chitransh"
PASSWORD="reshushrey@2027"
#DATABASE_CONNECTION=f'mssql://{USERNAME}:{PASSWORD}@{SERVER}/{DATABASE}?driver={DRIVER}'"""
table_name="bookdetails"

engine=create_engine("mssql+pyodbc://@DESKTOP-JKOITFK\SQLEXPRESS/newdatabase?driver=SQL SERVER NATIVE CLIENT 11.0")

connection=engine.connect()


details={}

def bookdetails():
    print("enter the book details:")    
    name=input("enter the name of the book:")
    
    
    author=input("enter the author of the book:")
    year=int(input("enter the year of the book:"))  
    publisher=input("enter the publisher of the book:")
    quantities=int(input("enter the quantities of the book:"))
       
    next_action=int(input("details entry completed. Press 1 for another entry, else press 2 for exit:"))
    
    details={"BookName":[name],"Author":[author],"Year":[year],"Publisher":[publisher],"Quantities":[quantities]}
    
    dict_df=pd.DataFrame(details)
    
    #print(dict_df)
    
    create_table=dict_df.to_sql(table_name,connection,if_exists="append",index=False)    
    
    
    if next_action==1:
        bookdetails()
    else:
        authorized()

def issuebooks():
    print("issue the books")
    issue_book=input("which book to issue:")
    
    frame=pd.read_sql("select Quantities from bookdetails where BookName = '{}'".format(issue_book),connection)
    
    updated_value_query=(update(bookdetails).values(Quantities=(int(frame.values)-1)).where(bookdetails.BookName=='{}'.format(issue_book)))
    connection.execute(updated_value_query)
    
    
    
    
def depositbooks():
    print("deposit the books")



def authorized():
    action=int(input("enter 1 for entering book details, enter 2 to issue books, enter 3 to deposit the book, enter 4 for exit:"))
    if action==1:
        bookdetails()
    elif action==2:
        issuebooks()
    elif action==3:
        depositbooks()
    #else:
      #  main()

def enter_func(username,password):
    if username not in librarian.keys():
        print("you are not authorized to enter")
    else:
        if password==librarian[username]:
            print("enter")
            authorized()
        else:
            print("password donot match,try again")
            #main()
 
while True:
    first=int(input("press 1 to login, 2 for exit:"))

    if (first==1):
        librarian={"deepika":"chiku","pragya":"praveen"}
        username=input("enter the username:")
        password=input("enter the password:")
        enter_func(username,password)
    
    else:
        break
    

我正在尝试制作一个书籍输入系统,为此我正在尝试连接 SQL 和 python。当我尝试使用更新查询更新 SQL 中的值时,它会显示错误

press 1 to login, 2 for exit:1

enter the username:deepika

enter the password:chiku
enter

enter 1 for entering book details, enter 2 to issue books, enter 3 to deposit the book, enter 4 for exit:2
issue the books

which book to issue:shiva2
Traceback (most recent call last):

  File "<ipython-input-1-df831d64649f>", line 1, in <module>
    runfile('C:/Users/hp/Desktop/project_part1.py', wdir='C:/Users/hp/Desktop')

  File "C:\Users\hp\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\hp\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/hp/Desktop/project_part1.py", line 101, in <module>
    enter_func(username,password)

  File "C:/Users/hp/Desktop/project_part1.py", line 89, in enter_func
    authorized()

  File "C:/Users/hp/Desktop/project_part1.py", line 77, in authorized
    issuebooks()

  File "C:/Users/hp/Desktop/project_part1.py", line 61, in issuebooks
    updated_value_query=update(bookdetails).values(Quantities=frame-1).where("BookName=='{}'".format(issue_book))

  File "<string>", line 2, in update

  File "C:\Users\hp\Anaconda3\lib\site-packages\sqlalchemy\sql\dml.py", line 735, in __init__
    ValuesBase.__init__(self, table, values, prefixes)

  File "C:\Users\hp\Anaconda3\lib\site-packages\sqlalchemy\sql\dml.py", line 201, in __init__
    self.table = _interpret_as_from(table)

  File "C:\Users\hp\Anaconda3\lib\site-packages\sqlalchemy\sql\selectable.py", line 49, in _interpret_as_from
    raise exc.ArgumentError("FROM expression expected")

ArgumentError: FROM expression expected

这是我面临的错误。它是说 FROM 表达式是预期的,但是当我在 SQL 中编写查询时,没有写入 FROM 表达式。我想更新 SQL 表中减去的值。

【问题讨论】:

    标签: python sql-server python-3.x database sqlalchemy


    【解决方案1】:

    我无法重现您的确切错误,但这一行

        updated_value_query=(update(bookdetails).values(Quantities=(int(frame.values)-1)).where(bookdetails.BookName=='{}'.format(issue_book)))
    

    需要进行一些更改才能工作:

    • 名称bookdetails 指的是函数 bookdetails,因此它不是update 的有效参数,它需要Table 对象或类似对象
    • where 子句中,Quantities 属性必须通过表的columnsc 属性访问
    import sqlalchemy as sa
    ...
    
    # Create a table object that maps to the table in the database
    bookdetails_table = sa.Table(table_name, sa.MetaData(), autoload_with=engine)
    
    # Use the table object in the query
    updated_value_query = (
        update(bookdetails_table)
        .values(Quantities=(int(frame.values) - 1))
        .where(bookdetails_table.c.BookName == '{}'.format(issue_book))
    )
    
    

    您的代码实际上并不需要 Pandas,您可以将其替换为 SQLAlchemy Core insertsupdates。例如(假设 SQLAlchemy 1.4+)

    from sqlalchemy import create_engine, update
    import sqlalchemy as sa
    
    
    table_name = 'bookdetails'
    
    engine = create_engine(...)
    
    
    # Create a table and assign it to a global variable.
    # Lowercase table and column names cause fewer problems than mixed or upper case
    metadata = sa.MetaData()
    book_table = sa.Table(
        table_name,
        metadata,
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('bookname', sa.String(128)),
        sa.Column('author', sa.String(128)),
        sa.Column('year', sa.Integer),
        sa.Column('publisher', sa.String(128)),
        sa.Column('quantities', sa.Integer),
    )
    book_table.create(engine, checkfirst=True)
    
    def bookdetails():
        print('enter the book details:')
        name = input('enter the name of the book:')
    
        author = input('enter the author of the book:')
        year = int(input('enter the year of the book:'))
        publisher = input('enter the publisher of the book:')
        quantities = int(input('enter the quantities of the book:'))
    
        next_action = int(
            input(
                'details entry completed. Press 1 for another entry, else press 2 for exit:'
            )
        )
    
        details = {
            'bookname': name,
            'author': author,
            'year': year,
            'publisher': publisher,
            'quantities': quantities,
        }
    
        insert = book_table.insert().values(**details)
        with engine.begin() as conn:
            conn.execute(insert)
    
        if next_action == 1:
            bookdetails()
        else:
            authorized()
    
    
    def issuebooks():
        print('issue the books')
        issue_book = input('which book to issue:')
    
        # Here we don't need to select and then update: we can express the update
        # as an operation on the column.
        updated_value_query = (
            update(book_table)
            .values(quantities=book_table.c.quantities - 1)
            .where(book_table.c.bookname == issue_book)
        )
        with engine.begin() as conn:
            conn.execute(updated_value_query)
    

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2018-02-19
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多