【问题标题】:can we take user input using python for mysql table values?我们可以使用 python 为 mysql 表值获取用户输入吗?
【发布时间】:2021-01-09 18:08:39
【问题描述】:

我尝试输入,但显示错误。

引发错误。ProgrammingError(

ProgrammingError: SQL 语句中未使用所有参数

我尝试过的部分代码,

`#D_O_B

import datetime
 year = int(input('Enter birth year'))
 month = int(input('Enter birth month'))
 day = int(input('Enter birth day'))
 D_O_B = datetime.date(year, month, day)
 
 #Age
 A=int(input("Enter age"))
sql = """INSERT INTO PLAYER_DETAILS(
   Name,DATE_OF_BIRTH ,Age ,Federation ,Elo_RATING ,Title)
   VALUES ( %s,%d ,(%d %b %y), %s,%d , %s)"""

 val = (N,D_O_B,A,Fed,RATING,T)
 cursor.execute(sql, val)

 db.commit()

【问题讨论】:

  • 对所有占位符使用%s。还有子表达式(%d %b %y) 应该做什么?
  • 错误消息只是告诉占位符的数量大于您输入字符串的变量数量。这甚至是真的:8 > 6。

标签: python mysql database-connectivity


【解决方案1】:
pip install pyodbc

pyodbc 是 Python 的开源 odbc 驱动程序,可让您连接 sql, 联系

import pyodbc    
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')

然后创建光标

cursor = cnxn.cursor()

然后像在 sql 查询中一样创建查询,在任何你想使用用户输入的地方,将其替换为 ? 将执行的第二个参数添加为 array 并在数组中输入各自的值

cursor.execute("""
    select user_id, user_name
      from users
     where last_logon < ?
       and bill_overdue = ?
""", [datetime.date(2001, 1, 1), 'y'])

如果你不想使用数组作为第二个参数,你可以传递多个参数,但它也应该是各自的

cursor.execute("insert into products(id, name) values (?, ?)", 'pyodbc', 'awesome library')

并在插入更新或删除后提交

cnxn.commit()

您可以在官方文档Getting Started 中找到更多信息

【讨论】:

  • 并为获取日期执行类似 this year = int(input('Enter a year')) month = int(input('Enter a month')) day = int(input('Enter a day')) date1 = datetime.date(年、月、日)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2021-03-01
  • 1970-01-01
  • 2018-09-20
  • 2011-08-11
相关资源
最近更新 更多