【问题标题】:Enter data into a SQL table in python?在 python 中将数据输入到 SQL 表中?
【发布时间】:2020-12-09 05:08:09
【问题描述】:

我正在制作一个连接到 SQL 数据库的程序,以便我输入数据。我不想手动将数据输入表中,而是想让一个程序来做。所以它会问我一系列问题,然后将答案输入到表格中。我不知道该怎么做。我的问题最后是光标执行。

我不确定如何将输入答案合并到该执行函数中。会是这样吗? .format 显示为字符串,所以我不确定如何实现。

VALUES
('{}'.format(category), '{}'.format(description), '{}'.format(date), '{}'.format(price), '{}'.format(vehicle))

下面是代码:

import time
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=TJDESKTOPPC;'
                  'Database=carparts;'
                  'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('''
              SELECT * FROM carparts.dbo.modifications
           
               ''')
conn.commit()

# Menu starts below

database = "carparts"
print("Welcome to the program!")
print()
print("You are connected to {} database".format(database))
print()
print()
print("The current columns in the table are...")
print()
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=TJDESKTOPPC;'
                  'Database=carparts;'
                  'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('SELECT * FROM carparts.dbo.modifications where 1=2')
headers = [i[0] for i in cursor.description]
print(headers)
print()
print("Categories are: engine, suspension, exhaust, or transmission")
print()
category = str(input("Please enter category: "))
print()
description = str(input("Please enter the description of the part: "))
print()
purchase_date = input("Please enter the purchase date in (YYYY-MM-DD): ")
print()
price = int(input("Please enter the price amount: "))
print()
vehicle = str(input("What vehicle is this for? (Model): "))
print()
print("Thanks!")
time.sleep(3)
print("\n" * 5)  # This will the clear screen of any previous code
print("Adding the category, description, purchase date, price, and vehicle to the table...")
time.sleep(2)

cursor.execute('''
            INSERT INTO carparts.dbo.modifications (category, description, purchase_date, price, 
vehicle)
            VALUES
            ('exhaust', 'Flowmaster Cat-back Exhaust', '2015-12-08', '551', 'focus_st')
           ''')
conn.commit()

上面INSERT INTO 的 sn-p 确实有效,但我需要手动输入值。那么如何在该字符串中获取变量输入(类别、描述、日期等)?

【问题讨论】:

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


【解决方案1】:

试试这个,

在这里您需要提供您想要插入的变量数据,并且还需要在单引号中添加 {},例如“{}”。 这样您在以格式 "'{}'".format("category_input") 提供值后看起来像 'category_input' 并且如果您有数字则不起作用。

cursor.execute('''INSERT INTO carparts.dbo.modifications (category, description, 
    purchase_date, price, vehicle) VALUES ('{}', '{}', '{}', '{}', '{}')'''.format(category, description, purchase_date, price, vehicle))

【讨论】:

  • 非常感谢!我刚刚错过了 .format 需要去的地方!非常感谢 Vishal,现在可以完美运行了!
  • 很高兴听到这个消息!
猜你喜欢
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多