当我运行它时,它会给我这样的错误:
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
这是我的代码:
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()
答案 0 :(得分:1)
raw_input
始终返回字符串值。这里的第一条规则是验证来自用户输入的数据并在需要时进行转换。使用input
是一个坏主意。第二个问题是向表中插入行。请始终使用sqlite的占位符,例如:
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()
不要使用;
:) Python不关心它们,但不需要它们。