我是python的新手,我正在尝试编写一个脚本,该脚本将接受来自用户的输入,并将存储在SQL Server数据库中。 但我不知道这样做的适当方法。我试过这个,但它不起作用并抛出错误。
此外,我想采取日期输入,如何做到这一点。
import pyodbc
from datetime import datetime
class data:
def __init__(self):
self.name=raw_input( "Enter Name: ")
self.section=raw_input( "Enter section: ")
## eon=raw_input( "Enter date : ")
## feon=datetime.strptime( eon,'%Y, %m, %d')
a=data()
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=KIRAN-PC;DATABASE=testing')
cursor = cnxn.cursor()
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (a.name,a.section,'2013-01-01')")
cnxn.commit()
输出:
Enter Name: adam
Enter section: A
Traceback (most recent call last):
File "C:/Python33/data1", line 14, in <module>
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (a.name,a.section,'2013-01-01')")
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The multi-part identifier "a.name" could not be bound. (4104) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The multi-part identifier "a.section" could not be bound. (4104)')
>>>
答案 0 :(得分:1)
使用参数时使用问号会更好。您可以这样使用它:
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (?,?,"2013-01-01")",(a.name,a.section))
编辑:您应该查看here以获取有关插入数据的简单示例。