简体   繁体   中英

Userinput from Python will not be transferred to SQL Server table

I hope you guys can help me. I'm setting up a login database, where users enter their information, and the information will be transferred to a SQL Server database.

My connection between Python and SQL Server is working, but I cannot figure out how to make the user inputs from Python into a variable that is transferable to the SQL Server table. Right now where it says 'Peter Hansen', my user input should be instead. Any suggestions regarding optimization and so on are welcome as well. I'm quite new to Python, so treat me thereafter:)

import pyodbc

Name = input('What is your name?')

conn = pyodbc.connect(
    'Driver={SQL Server};'
    'Server=DESKTOP-H10O5O1\SQLEXPRESS;'
    'Database=Logins;'
    'Trusted_Connection=yes;'
)

cursor = conn.cursor()
cursor.execute('SELECT * FROM dbo.LoginTable')

cursor.execute('''
                INSERT INTO dbo.LoginTable (Name)
                VALUES ('Peter Hansen')
                ''')
conn.commit()

Thanks for the reply. I ended up going in a slightly different direction, which works for my needs:

import pyodbc

Name = input('What is your name?')
Username = input('What is your username?')
Password = input('What is your password?')

conn = pyodbc.connect(
    'Driver={SQL Server};'
    'Server=DESKTOP-H10O5O1\SQLEXPRESS;'
    'Database=Logins;'
    'Trusted_Connection=yes;'
)

cursor = conn.cursor()
cursor.execute("INSERT INTO dbo.LoginTable (Name, Username, Password) VALUES(?,?,?)", Name, Username, Password)
conn.commit()
cursor.execute('''
            INSERT INTO dbo.LoginTable (Name)
            VALUES
            ( ? )
            ''', (Name, ))

Try this if you are using python 3.5 and newer:

cursor.execute(f'''
            INSERT INTO dbo.LoginTable (Name)
            VALUES
            ('{Name}')
            ''')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM