Facing issue in writing Nested Dictionaries to Newly Created SQL Table - python

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)));

Related

sorry for that kind of question but i must ask . How to create a table in SQLITE to ask me what to call a table

E.g. After launching the program:
It is in interactive mode
We are asked what name we want to create the database with;
After creating the database, the program asks us under what name to create the table in the database;
In the next step, the program asks us how many columns the table should have;
Enter the names of the mentioned number of columns and their types interactively;
Finally, create a database and a table with the columns indicated in it;
import sqlite3
connection = sqlite3.connect(input("Enter the name for base: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
columns_name = []
columns_amount = int(input("Enter amount of coulms and name them: "))
for item in range(columns_amount):
item = input("input theme mane of column: ")
columns_name.append(item)
cursor.execute("DROP TABLE IF EXISTS "+table_name+"" )
cursor.execute("CREATE TABLE IF NOT EXISTS "+ table_name +" ("+columns_name[0]+" INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+columns_name[1]+" TEXT, "+columns_name[2]+" TEXT, "+columns_name[3]+" TEXT )")
connection.commit()
You can just create the sql string for table creation inside the loop like -
import sqlite3
connection = sqlite3.connect(input("Enter the name for database: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
sql_string = "CREATE TABLE IF NOT EXISTS {} (".format(table_name)
columns_amount = int(input("Enter amount of columns: "))
for i in range(columns_amount):
column = input("input the name of column {}: ".format(i + 1))
datatype = input("input the type of column: ")
# You may want to check here whether column name and data type is valid or not
sql_string += "{} {},".format(column, datatype)
# remove the last extra comma
sql_string = sql_string[:-1]
sql_string += ")"
print(sql_string)
cursor.execute("DROP TABLE IF EXISTS {}".format(table_name))
# Finally create the table
cursor.execute(sql_string)
connection.commit()
Your code will not work because during table creation you are assuming that there are 3 columns which may not be true. So accessing those indices of columns_name might throw exception.

Write nested Python dictionary into 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 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)

python dictionary to sqlite insert

As I m reading about SQLLite3 and Python, I tried this simple dictionary to DB approach. I have tried a few stackoverflow forums but now able to figure out how to get this data from dictionary to database and then print it. Code below:
import sqlite3
user_dir={}
#connect a built in function to connect or create db
conn=sqlite3.connect('phonebook.db')
#Create a cursor function which allows us to do sql operations
crsr=conn.cursor()
#Create a Table
#crsr.execute(""" Create Table phonebook(
# f_name text,
# phone text)
# """)
def create_user():
while True:
rsp=input('Create new user: Y/N ?')
if rsp=='y':
f_name = input('Enter first name: ')
#First name cannot be empty
while (len(f_name)==0):
print('First name cannot be empty')
f_name = input('Enter first name: ')
phone = input('Enter phone number: ')
user_dir[f_name]=phone
#crsr.execute("INSERT INTO phonebook VALUES (?,?)", [user_dir["f_name"], user_dir["phone"]])
#crsr.executemany("INSERT INTO phonebook VALUES (?,?)", user_dir)
columns = ', '.join(user_dir.keys())
sql = "INSERT INTO phonebook VALUES (?,?)" % ('phonebook', columns)
crsr.execute(sql, user_dir.values())
if rsp=='n':
break
crsr.execute("SELECT * from phonebook")
print(crsr.fetchall())
Errors are different for each commented out lines. Thanks for your time and help.

How to store results from SQL query and use it?

I am trying to see whether the type is either a the letter "T" or between number 1-6 for the specific data entry found with name and password.
sql = 'SELECT type FROM table name WHERE name = "{}" AND password = "{}"'.format(username, password)
and then in psedocode i need something like:
if type =< 5:
int()
elif type = "T"
string()
I am using python 2.7
Here is a full script that will query the mysql DB, and use your above-mentioned logic to print the values. I've included the python code as well as the sample database code for this test case. Let me know if you have any questions.
Python
import pymysql
connection = pymysql.connect(user='username', passwd='password',
host='localhost',
database='database')
cursor = connection.cursor()
NAME = 'Person_A'
PASSWORD = 'Password_A'
query = ("SELECT * FROM My_TABLE WHERE NAME = '%(1)s' AND PASSWORD = '%(2)s';" % {"1" : NAME, "2" : PASSWORD})
cursor.execute(query)
for item in cursor:
type = item[0]
if type.isdigit():
if int(type) <6:
print('Type is a number less than 6')
else:
print('Type is a number but not less than 6')
else:
if type == 'T':
print('Type is a string == T')
else:
print('Type is a string but not the letter T')
MYSQL
CREATE TABLE MY_TABLE (TYPE VARCHAR(255), NAME VARCHAR(255), PASSWORD VARCHAR(255));
INSERT INTO MY_TABLE VALUES ('T','Person_A','Password_A'),('4','Person_A','Password_A'),('7','Person_B','Password_B'),('t','Person_C','Password_C');

Trying to search a column on SQLite Python so that it only returns the information searched

New to Python and Databases
I have a database table set up with a column of usernames. I want the user to be able to search through the table via a raw_input and only return the values which are associated with that user name.
E.g. user searches for Bill and it only displays Bill's records ordered by a specified column
This is what I have so far but its obviously VERY wrong, hope someone can help:
def find_me(db, column_name):
db = sqlite3.connect(db)
cursor = db.cursor()
name = raw_input("Please enter your username: ")
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
cursor.execute("SELECT * FROM username ORDER BY "+column_name+" ASC")
name = cursor.fetchone()
next = cursor.fetchone()
Thank you in advance
You want to make the query similar to the following:
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
This uses query parameters, so it's correctly escaped for the data provided. Then just adapt this to SELECT * and whatever else you want from the result.
Try working with this:
name = raw_input("Please enter your username: ")
query = "SELECT * FROM username WHERE name=? ORDER BY {0}".format(column_name)
cursor.execute(query, (name,))
for row in cursor:
print row

Categories