简体   繁体   English

我如何将 python 中的值插入 sql 服务器

[英]how do i insert values from python into sql server

hi i am looking to insert these 3 values into my SQL database table that has columns: email, cardnumber, dateandtime here is my code:嗨,我希望将这 3 个值插入到我的 SQL 数据库表中,该表具有以下列:email、cardnumber、dateandtime 这是我的代码:

email = input("Email: ")
cardnumber = int(input("Enter card number:"))
now = datetime.now()
now = now.strftime('%Y-%m-%d %H:%M:%S')
newrowforsql()

my code for the query is:我的查询代码是:

def newrowforsql():
    query = """\
        insert into table1 (email,cardnumber,dateandtime)
        values(email,cardnumber,now)"""
    insertnewrow = execute_query_commit(conn, query)

I cant seem to insert the values我似乎无法插入值

my code for executing the query and committing it is:我执行查询并提交它的代码是:

def execute_query_commit(connection, query):
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        connection.commit()
        print("Query executed and committed")
    except pyodbc.Error as e:
        print(f"The error '{e}' occurred")

As "azro" mentioned correctly you didn't put in the variable content to the query, you just put in the name of the variable which contains the information you want.正如“azro”正确提到的那样,您没有将变量内容放入查询中,您只需输入包含所需信息的变量的名称。 What you need to change is the following:您需要更改的内容如下:

def newrowforsql():
    query = """\
        insert into table1 (email,cardnumber,dateandtime)
        values(email,cardnumber,now)"""
    insertnewrow = execute_query_commit(conn, query)

to

def newrowforsql():
    query = """\
        insert into table1 (email,cardnumber,dateandtime)
        values({theEmail},{theCardnumber},{now})""".format(theEmail=email, theCardnumber=cardnumber, now=now)
    insertnewrow = execute_query_commit(conn, query)

This is one of the most used options to manipulate strings in python.这是在 python 中操作字符串的最常用选项之一。 But if you are using python3.7+ (maybe from Python3.6 and up, but I'm not sure) there is a much better and faster option to manipulate strings, it's name is "f-strings".但是如果您使用的是 python3.7+(可能来自 Python3.6 及更高版本,但我不确定)有一个更好更快的选项来操作字符串,它的名称是“f-strings”。

Here is the same solution but with f-strings instead of the method str.format这是相同的解决方案,但使用f-strings而不是str.format方法

def newrowforsql():
    query = f"""\
        insert into table1 (email,cardnumber,dateandtime)
        values({email},{cardnumber},{now})"""
    insertnewrow = execute_query_commit(conn, query)

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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