I want to insert a row into my table, but I am getting an error. Where am I going wrong?
CREATE TABLE person (
name VARCHAR(40),
birthday DATE,
PRIMARY KEY (name)
);
Now in python I try to insert a person with the following statement...
curs = connection.cursor
name = input("Name: ")
birthday = input("Birthdate(yyyy-mm-dd): ")
insert = """insert into people(name, birthday) values (:name,:birthday)"""
curs.execute(insert,{'name':name,'to_date(birthday, "yyyy-mm-dd")':birthday})
I get the following error:
curs.execute(insert,{'name':name,'to_date(birthday, "yyyy-mm-dd")':birthday})
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
Figured it out, I was inserting the date wrong.
My syntax was incorrect and should have been:
curs = connection.cursor
name = input("Name: ")
birthday = input("Birthdate(yyyy-mm-dd): ")
insert = """insert into people(name, birthday) values (:name, to_date(:birthday, 'yyyy-mm-dd'))"""
curs.execute(insert,{'name':name, 'birthday':birthday})
Related
I need to prompt a user to create a student table, check if a table with such a name exists in the database, and if not create it.
import sqlite3
conn = sqlite3.connect('School')
print ("Database has been created")
def create_table():
TableName = input("Enter table name: ")
tb_create ="""CREATE TABLE , (TableName,) (ID INT PRIMARY KEY,title VARCHAR(10), forename VARCHAR(20),
surname VARCHAR(20))"""
tb_exists ="SELECT name FROM sqlite_master WHERE type='table' AND name= ?", (TableName,)
if not conn.execute(tb_exists).fetchone():
conn.execute(tb_create)
print ("Table created successfully")
else:
print ("Table Exists!")
I know its possible to inser user inputed value into a table, but how do I create a table with inputed name? What should go after CREATE TABLE? If I use , (TableName,) the code wont compile.
Also, once the new table has been added to database, how do I indicate its name in INSER INTO query?
def insert_data():
conn.execute("INSERT INTO TableName (ID,title,forename,surname)VALUES \
(234,'Mr','XXX','XXX'")
conn.commit()
The correct syntax for a CREATE TABLE statement is:
CREATE TABLE tablename(column1 datatype1, column2 datatype2, ....)
Since you want the user to provide the name of the table, you can do it with string interpolation, because you can't pass it with a ? placeholder in the sql query as aparameter:
tb_create = f"CREATE TABLE [{TableName}](ID INTEGER PRIMARY KEY, title TEXT, forename TEXT, surname TEXT)"
The table's name must be enclosed inside square brackets, just in case the user provided a name that is not valid (for example it starts with digit or contains spaces).
Also, if you want the column ID to be autoincrement, you must use INTEGER instead of INT for its data type.
Also, there is no VARCHAR data type in SQLite. Use TEXT.
You can define the variable TableName as global so that you can use it in all the functions, like insert_data().
Use string interpolation for the INSERT statement also.
import sqlite3
conn = sqlite3.connect("School")
print ("Database has been created")
TableName = ""
def create_table():
global TableName
TableName = input("Enter table name: ").strip()
tb_exists ="SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?"
if not conn.execute(tb_exists, (TableName,)).fetchone():
tb_create = f"CREATE TABLE [{TableName}](ID INTEGER PRIMARY KEY, title TEXT, forename TEXT, surname TEXT)"
conn.execute(tb_create)
print("Table created successfully")
else:
print("Table Exists!")
def insert_data():
if len(TableName) > 0:
conn.execute(f"INSERT INTO [{TableName}] (ID,title,forename,surname) VALUES (234,'Mr','XXX','XXX')")
conn.commit()
create_table()
insert_data()
The name of the table, or of the columns cannot be parameterized, so you must build the query string. It means that you should control that the entered name is sane because building query from strings is know to be a vector for SQL injection.
But most (if not all) SQL database allow to create a table if it does not already exists. The syntax is just:
CREATE TABLE table_name IF NOT EXISTS (
column_name type,
...)
So here, you could just do:
import re
...
def create_table():
TableName = input("Enter table name: ")
# control name:
if not re.match(r'\w*$', TableName):
raise IllegalValue("Invalid table name")
tb_create =f"""CREATE TABLE {TableName} IF NOT EXISTS (ID INT PRIMARY KEY,title VARCHAR(10),
forename VARCHAR(20), surname VARCHAR(20))"""
conn.execute(tb_create)
While trying to insert the Query in MYSql through python Script, I am facing an error as "1054 (42S22): Unknown column 'Abhinav' in 'field list'". There is some minor syntax error , but I am not able to Find it.
my_cursor.execute("CREATE DATABASE IF NOT EXISTS task")
my_cursor.execute("CREATE TABLE IF NOT EXISTS EmployeeList(user_id INT AUTO_INCREMENT PRIMARY KEY,EMPID INT, Emp_Name VARCHAR(100),Designation VARCHAR(100), Role VARCHAR(100), Updated_by VARCHAR(100), LastUpdate TIMESTAMP DEFAULT NOW())")
EMP_ID = input("Enter the Employement Id : ")
EmpName = input("Enter the Employee Name : ")
Designations = input("Enter the Designation : ")
Roles = input("Enter the Role : ")
Updatedby = input("Enter the name of the Person updated by: ")
try:
sql_insert_query = f"INSERT INTO EmployeeList(EMPID,Emp_Name,Designation,Role,Updated_by) VALUES ({EMP_ID},{EmpName},{Designations},{Roles},{Updatedby})"
my_cursor.execute(sql_insert_query)
mydb.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to update record to database: {}".format(error))
finally:
if (mydb.is_connected()):
my_cursor.close()
mydb.close()
print("MySQL connection is closed")
user input details has to be given after running the script.
Enter the Employement Id : 1
Enter the Employee Name : Abhinav
Enter the Designation : Software Engineer
Enter the Role : GE
Enter the name of the Person updated by: Abhi
Error -
Failed to update record to database: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Engineer,GE,Abhi)' at line 1
MySQL connection is closed
Rather than format the INSERT statement by hand, you should add placeholders and pass the actual values as params to the execute method:
sql_insert_query = "INSERT INTO EmployeeList(EMPID,Emp_Name,Designation,Role,Updated_by) VALUES (%s,%s,%s,%s,%s)"
my_cursor.execute(sql_insert_query, params=(EMP_ID, EmpName, Designations, Roles, Updatedby))
Here's some documentation: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
I need to write the nested dictionaries in the newly created SQL Table.
I think I have made some mistake in creating new table in SQL by mentioning its column also. Could anyone please review the code & tell me whether this step is correct or not.
db = conn.connect(
host ="Localhost",
user ="root",
passwd ="admin",
database = "EMPLOYEE_DETAILS_00"
)
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Details ( User_ID VARCHAR(255), Name VARCHAR(255), Age VARCHAR(255) ) ")
I need to write a nested Python dictionary into a SQL table. I'm trying to do it by using a for loop.
This is the code I'm trying to run:
user_details = {}
create_user_ID = input(" Enter the user ID : ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
for v in user_details.values():
cols = v.keys()
vals = v.values()
sql = "INSERT INTO Details ({}) VALUES ({})".format(
', '.join(cols),
', '.join(['%s'] * len(cols)));
cursor.execute(sql, vals)
If I run this code I'm getting the following error
Error : Couldn't process parameters
Could anyone please review the code and tell me where I've made the mistake, whether in creating SQL Table or in FOR Loop.
Thanks in advance !!
I think issue is when you try to create sql query inside the loop.try this one
sql = "INSERT INTO Details {}) VALUES ({})".format(
', '.join(cols),
', '.join(map(str,vals)));
I think I have made some mistake in creating new table in SQL by mentioning its column also. Could anyone please review the code let me know your thoughts on this
db = conn.connect(
host ="Localhost",
user ="root",
passwd ="admin",
database = "EMPLOYEE_DETAILS_00"
)
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Details ( User_ID VARCHAR(255), Name VARCHAR(255), Age VARCHAR(255), Occupation VARCHAR(255), Department VARCHAR(255), Salary VARCHAR(255), Address VARCHAR(255) ) ")
I need to write a nested Python dictionary into a SQL table. I'm trying to do it by using a for loop but I'm getting the following error:
Error : Couldn't process parameters
Can anyone provide me with any suggestions on this?
This is the code I'm trying to run:
user_details = {}
create_user_ID = input(" Enter the user ID : ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
for v in user_details.values():
cols = v.keys()
vals = v.values()
sql = "INSERT INTO Details ({}) VALUES ({})".format(
', '.join(cols),
', '.join(['%s'] * len(cols)));
cursor.execute(sql, vals)
I would say your problem is at the last line, when you try to do cursor.execute(sql,(val,)).
In Python 3 dict.keys() and dict.values() doesn't return lists, but some dictionary view objects wrapping the data, so what you're getting from (val,) is a single value tuple with one dict_values object.
Try using just val as #niteshbisht suggested or list(val) or tuple(val) if that still doesn't work.
Please see also Python nested dictionary with SQL insert, as it looks like you're trying to address the same problem.
DON'T use the most obvious one (%s with %) in real code, it's open to attacks.
sql = ("INSERT INTO Details ? Values ?" ,(col, placeholders))
cursor.execute(sql,val)
I am trying to get the user input the information so it can be stored in a database using SQLite3 but the error: "sqlite3.OperationalError: no such column: first_name" keeps popping up and I don't know why. Any suggestions?
import sqlite3
connection = sqlite3.connect('database.db')
cursor = connection.cursor()
create_table = '''
CREATE TABLE example (
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1));'''
cursor.execute(create_table)
first_name = input('First name : ')
surname = input('surname: ')
gend = input('Gender: ')
add_staff = '''INSERT INTO example (fname, lname, gender)
VALUES (first_name, surname, gend);'''
cursor.execute(add_staff)
cursor.execute('SELECT * FROM example')
result = cursor.fetchall()
for r in result:
print(r)
cursor.execute('SELECT * FROM example')
I would like to stick to sqlite3 rather than using another database library within python. Thanks.
You need to pass the values of your variables to your SQL command, using placeholders.
add_staff = '''INSERT INTO example (fname, lname, gender)
VALUES (?, ?, ?);'''
cursor.execute(add_staff, (first_name, surname, gend))