python dictionary to sqlite insert - python

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.

Related

taking Input of datatype and its size from user to modify column in a table in Python database

I am a newbie to Sql and database concepts. so I am trying to make a program which does the basic tasks done by replacing the idea of entering commands by using functions in MySQL( like creating a table in database, adding records, modifying table etc). I now want to take input from user which include column name, its datatype, its size so that user can decide the basic structure of a new column.
So , I came across something called string formatting which I used a bit to enter variables into the Sql commands. so I tried using this concept in this case. But it gives syntax error.
Can somebody suggest me a solution to this and tell me my mistake.
I apologize for my bad grammar
Thanks
here is the code
##importing mysql connector
import mysql.connector
## Creating connection object
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "milkshake#343",
database = 'practice'
)
## defining a cursor object
cursor_obj = mydb.cursor()
##creating a table (uncommnent to edit and execute)
def table_create():
cursor_obj.execute("CREATE TABLE test3(name VARCHAR(50),ageINT unsigned,person_id int PRIMARY KEY AUTO_INCREMENT)")
## Describing the table (uncommnent to edit and execute)
def table_desc():
cursor_obj.execute("describe test3")
for x in cursor_obj:
print(x)
##creating a function to enter values into the table
def inputer():
#taking records from user to enter in the table
name = input("please enter the name to enter into the table:")
age = int(input("please enter the age to enter into the table:"))
#Entering values into the table
cursor_obj.execute('insert into test3 values(%s,%s)',(name,age))#you may change table name here if you want
##creating a comitt option
def commit():
mydb.commit()
##function to display the whole content of the table
def whole_table():
cursor_obj.execute("select * from test3")
for x in cursor_obj:
print(x)
##adding column into the table
def column_add():
new_column = input("Enter the name of the new column:")
data_type = input("Enter the data type of new column:")
size = int(input("Enter the size of the new column:"))
cursor_obj.execute("alter table test3 add column %s %s(%s)",(new_column,data_type,size))
column_add()
commit()
I am going to add more functions in this

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.

Facing issue in writing Nested Dictionaries to Newly Created SQL Table

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

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

Can't get the last row id from SQLITE3 database

I have a script that asks for input, and that input is then inserted into a table.
The next time the script is run, I'd like for it to tell the user what id the last input has.
The table looks like: id INTEGER PRIMARY KEY AUTOINCREMENT, userid TEXT, domain TEXT, password TEXT, webserver TEXT, sqlserver TEXT
I was told I could use SELECT seq from SQLITE_SEQUENCE WHERE name='table_name' but it yields the following text: instead of the id from the last row.
Please note that I'm an extremely new Python / SQLite3 coder!
For your reference, the code sofar looks like this:
#!/usr/bin/python
import os, sys, sqlite3
######## CHECK SYSTEM COMPATIBILITY ########
if os.name =='posix':
os.system("clear")#CLEAR SCREEN#
pass
else:
sys.exit("Operating System is not supported")
######## END CHECK SYSTEM COMPATIBILITY ########
######## CHECK IF SCRIPT IS RUN AS ROOT ########
#if os.geteuid() != 0:
# sys.exit("Script must be run as root")
#else:
# pass
####### END CHECK IF SCRIPT IS RUN AS ROOT ########
####### CREATE DATABASE AND CHECK IF TABLE EXISTS ##########
conn = sqlite3.connect("dat.db")
c = conn.cursor()
c.execute ('''CREATE TABLE IF NOT EXISTS kunder
(id INTEGER PRIMARY KEY AUTOINCREMENT, userid TEXT, domain TEXT, password TEXT, webserver TEXT, sqlserver TEXT)''')
conn.commit()
print c.execute ("SELECT seq from SQLITE_SEQUENCE WHERE name='kunder'")
conn.close()
######## DONE CREATE DATABASE AND CHECK IF TABLE EXISTS #########
###### ASK FOR INPUT ##########
########### HERE NEEDS TO BE A CHECK TO DETERMINE THE LATEST USERID - ALSO NEEDS TO BE FOR WEBSERVER AND PASSWORD #################
userid = raw_input("Enter userid: ")
########### HERE NEEDS TO BE A CHECK TO SEE IF USERID EXISTS!!!!!#####################
domain = raw_input("Enter domain: ")
password = raw_input("Enter password: ")
########### NEEDS TO BE A WAY TO AUTOGENERATE A PASSWORD!!! ####################
webserver = raw_input("Enter webserver: ")
sqlserver = raw_input("Enter sqlserver: ")
###### FINISHED ASK FOR INPUT #######
######## DATABASE ###########
conn = sqlite3.connect("dat.db")
c = conn.cursor()
c.execute ("INSERT INTO kunder (userid, domain, password, webserver, sqlserver) VALUES (?,?,?,?,?)", (userid, domain, password, webserver, sqlserver))
conn.commit()
conn.close()
####### DONE WITH DATABASE ##########
The SQL statement SELECT max(id) FROM table_name should give you the maximum id. If you're auto-incrementing then this would be the same as the last inserted.
Edit: To get the actual value in python means reading it from the cursor:
cursor = sqlite3.execute('SELECT max(id) FROM table_name')
max_id = cursor.fetchone()[0]
fetchone() returns the first row from the select statement as a tuple (unless a row_factory is used), so fetchone()[0] will, in this case, return the first (and only) column in the first (and only) row, i.e. the max(id).
See http://docs.python.org/2/library/sqlite3.html for more info.
Try using sqlite3_last_insert_rowid()
import sqlite3
data_person_name = [('Michael', 'Fox'),
('Adam', 'Miller'),
('Andrew', 'Peck'),
('James', 'Shroyer'),
('Eric', 'Burger')]
con = sqlite3.connect(":memory:")
c = con.cursor()
c.execute('''CREATE TABLE q1_person_name
(name_id INTEGER PRIMARY KEY,
first_name varchar(20) NOT NULL,
last_name varchar(20) NOT NULL)''')
for data_person in data_person_name:
c.execute('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person)
# get the last rowid inserted
last_name_id = c.lastrowid
print(last_name_id)

Categories