Kaliya Mitesh
Kaliya Mitesh

Reputation: 3

How take input from as user as integer and how to put it sqlite query to get data?

When I run it it gives me error like these:

 Opened database successfully
 enter your name: dsf
 enter your salary: 324

Traceback (most recent call last):
 File "d1.py", line 13, in <module>
 VALUES ( \"" + name + "\", " +salary +")");
 TypeError: cannot concatenate 'str' and 'int' objects

Here is my code:

import sqlite3

conn = sqlite3.connect('employee.db'); 
print "Opened database successfully";


name=raw_input ("enter your name: ");
salary=input("enter your salary: "));

conn.execute("INSERT INTO emplo(NAME,SALARY) \
VALUES ( \"" + name + "\", " +salary +")");


conn.commit()
print "Records created successfully";
conn.close()

Upvotes: 0

Views: 2429

Answers (1)

gryf
gryf

Reputation: 21

raw_input always returns string value. First rule here is to validate data from user input and convert it, if needed. Using input for that is a bad idea. Second problem is with inserting row to the table. Please, always use placeholders for sqlite, like in your example:

import sqlite3
import logging


# open db in memory, you can use file instead
conn = sqlite3.connect(':memory:')
conn.execute('create table employee(id integer primary key autoincrement,'
             'name string, salary int)')
logging.info("Database successfully created")

name = raw_input('Enter your name: ')
salary = None
while salary is None:
    salary = raw_input('Enter your salary: ')
    # example of validating input - note, that `input` is not best way for
    # providing validation
    try:
        salary = int(salary)
    except ValueError:
        logging.warning('Provided salary is not an integer, try again.')
        salary = None

# Use placeholders. Second argument always have to be tuple
conn.execute('insert into employee(name, salary) values(?, ?)',
             (name, salary))
conn.commit()
logging.info('Record created successfully')

# let see what we have in db:
print conn.execute('select * from employee').fetchall()

conn.close()

And do not use ; :) Python don't care about them, but they are not needed.

Upvotes: 1

Related Questions