Reputation: 161
I am new to python and i am trying to write a script which will accept inputs from user and that will be stored in the SQL server database. But i don't know the appropriate method to do that. I have tried this but it is not working and throwing an error.
Also i want to take date input, how to do that.
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()
Output:
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)')
>>>
Upvotes: 0
Views: 7561
Reputation: 7735
It's better if you use question marks whilst using parameters. You might use it like this:
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (?,?,"2013-01-01")",(a.name,a.section))
EDIT: You should check here for a simple example about inserting data.
Upvotes: 1