SQLite + Python Data not saved in DB file - python

This is my first project with SQLite.
The code runs perfect I checked and the lines look perfect.
I supposed that due to lack of knowledge of SQLite I'm making a mistake.
Problem: The code runs perfect no problem. But when I finish it doesn't print the values or even save the values in the .db file.
Full Code:
import sqlite3
import datetime
import time
conn = sqlite3.connect('covid.db')
c = conn.cursor()
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = input('Please insert FULL NAME : \n ...')
i_email = input('Please insert EMAIL : \n ...')
i_number = input('Please insert PHONE NUMBER : \n ...')
print('Your data has been saved for acelerated contact, thank you.')
time.sleep(3)
def data_entry():
c.execute('INSERT INTO covidTrack VALUES(?,?,?)',
(i_name, i_email, i_number))
conn.commit()
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
def read_from_db():
c.execute('''SELECT * FROM covidTrack
WHERE datestamp
BETWEEN "2021-02-06 14:50:00" AND "2021-02-06 15:00:00"''')
conn.commit()
for row in c.fetchall():
print(row)
create_table()
data_entry()
dynamic_data_entry()
read_from_db()
c.close()
conn.close()
I suppose if something wrong with the way I use conn.commit().

import sqlite3
import datetime
import time
conn = sqlite3.connect('covid.db')
c = conn.cursor()
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = input('Please insert FULL NAME : \n ...')
i_email = input('Please insert EMAIL : \n ...')
i_number = input('Please insert PHONE NUMBER : \n ...')
print('Your data has been saved for acelerated contact, thank you.')
time.sleep(3)
def data_entry():
date, keyword = dynamic_data_entry()
c.execute('INSERT INTO covidTrack VALUES(?, ?, ?, ?, ?)', (i_name, i_email, i_number, date, keyword))
conn.commit()
def dynamic_data_entry():
keyword = 'nameofvenue'
date = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%M-%D %h:%m:%s'))
return date, keyword
def read_from_db():
c.execute('''SELECT * FROM covidTrack''')
conn.commit()
create_table()
data_entry()
read_from_db()
for row in c.fetchall():
print(row)
c.close()
conn.close()

change the code below (make the commit call part of the function that insert the data). Do it in dynamic_data_entry as well
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
to
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()

You do not actually commiting your executes. Move conn.commit after actual executes.

Related

sql python The value entered in the table is set first, the second is null

i create table
def sql_table_strategy():
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS strategy"
"(stra TEXT NOT NULL,"
"probability TEXT NOT NULL,"
" chat_id INTEGER UNIQUE)")
conn.commit()
cursor.close()
conn.close()
integraite strategy
def strategy_add(stra, ChatID):
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
val = (stra, ChatID)
sql = "INSERT OR IGNORE INTO strategy (stra,chat_id) VALUES (?,?)"
cursor.execute(sql, val)
conn.commit()
cursor.close()
conn.close()
add probability
def pr_add(probability, ChatID):
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
val = (probability,ChatID)
sql = "INSERT OR IGNORE INTO strategy (probability,chat_id) VALUES (?,?)"
cursor.execute(sql, val)
conn.close()
conn.close()
when I add the first strategy and then I add probability but in Columns probability is null
A solution for your problem.
def pr_add(probability, ChatID):
conn = sqlite3.connect('strategy.db', check_same_thread=False)
cursor = conn.cursor()
val = (probability,ChatID)
sql = "UPDATE strategy SET probability = ? WHERE chat_id = ?" --Change is here
cursor.execute(sql, val)
conn.close()
conn.close()

how to Make a sqlite3 database in python with 1 row

I was wondering if there is way to make a sqlite3 database in python with a Single row (record) of data and when i execute the code again it won't be made twice.
So far I have tried with to code:
conn = sqlite3.connect('db_M.db')
c = conn.cursor()
no1 = "Null"
no2 = "Null"
no3 = "Null"
value = 1
try:
c.execute("CREATE TABLE IF NOT EXISTS M_Memory(Name TEXT, Person TEXT, memory TEXT, value REAL)")
if True:
c.execute("INSERT INTO M_Memory(Name, Person, memory, value) VALUES (?, ?, ?, ?)",
(no1, no2, no3, value))
except:
print(" foo ")
conn.commit()
i solved my own problem .. please if you have any better code share it .. thanks guys
import sqlite3
conn = sqlite3.connect('db_M.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS M_Memory(Name TEXT, Person TEXT, memory TEXT, value REAL)")
text10 = input("what do you want to call the memory ?\n")
text11 = input("what or who the memory will be about?\n")
text12 = input("what do you want me to save in it ?\n")
def Get_The_Max_Function():
Max_Value = []
c.execute('SELECT MAX(value) FROM M_Memory')
lolo = c.fetchone()
if lolo[0] is None:
lolo = 0
Max_Value.insert(0, lolo)
else:
x = int((lolo[0]))
Max_Value.insert(0, x)
return Max_Value
def dynamic_data_entry(Max_Value):
Name = text10
Person = text11
memory = text12
value = Max_Value[0] + 1
c.execute("INSERT INTO M_Memory(Name, Person, memory, value) VALUES (?, ?, ?, ?)",
(Name, Person, memory, value))
conn.commit()
dynamic_data_entry(Get_The_Max_Function())
c.close()
conn.close()
Try this one:
c.execute("INSERT INTO M_Memory(Name, Person, memory, value)
SELECT ?, ?, ?, ?
EXCEPT
SELECT Name, Person, memory, value from M_Memory",
(no1, no2, no3, value) )
EXCEPT, which is MINUS in other databases (such as Oracle), makes sure the row will not not be inserted if another row is already there with all values equal.

Python 3 + SQLite check

Hello
I have a question about SQLite functions, maybe.
So, question:
How to check if name I set in Python is in certain column?
Example:
name = 'John'
Table name = my_table
Column name = users
Code details:
C = conn.cursor()
Please
Use parameter in the query as required. See the attached example for better understanding.
Sample SQLite code for searching value in tables
import sqlite3 as sqlite
import sys
conn = sqlite.connect("test.db")
def insert_single_row(name, age):
try:
age = str(age)
with conn:
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS USER_TABLE(NAME TEXT, AGE INTEGER);")
cursor.execute("INSERT INTO USER_TABLE(NAME, AGE) VALUES ('"+name+"',"+age+")")
return cursor.lastrowid
except:
raise ValueError('Error occurred in insert_single_row(name, age)')
def get_parameterized_row(name):
try:
with conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM USER_TABLE WHERE NAME = :NAME",
{"NAME":name})
conn.commit()
return cursor.fetchall()
except:
raise ValueError('Error occurred in get_parameterized_row(name)')
if __name__ == '__main__':
try:
return_id = insert_single_row("Shovon", 24)
return_id = insert_single_row("Shovon", 23)
return_id = insert_single_row("Sho", 24)
all_row = get_parameterized_row("Shovon")
for row in all_row:
print(row)
except Exception as e:
print(str(e))
Output:
('Shovon', 24)
('Shovon', 23)
Here I have created a table called USER_TABLE with two attributes: NAME and AGE. Then I inserted several values in the table and searched for a specific NAME. Hope it gives a way to start using SQLite in the project.

How do I make a return statement from this loop

I have this code and i need to get the lastrowid as a return statement. How can i fix it
def main():
while True:
#code here
for item in name2:#break
conn = sqlite3.connect("foods.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO INPUT33 (NAME) VALUES (?);", (name2,))
cursor.execute("select MAX(rowid) from [input33];")
conn.commit()
conn.close()
for rowid in cursor:break
for elem in rowid:
return rowid#this is not working
print(m)
You closed the database, so any cursor no longer has access to the data. Retrieve the data before closing. I am assuming here that you have a reason to re-open the database in a loop here.
def main():
while True:
for item in name2:
conn = sqlite3.connect("foods.db")
cursor = conn.cursor()
with conn:
cursor.execute("INSERT INTO INPUT33 (NAME) VALUES (?);", (name2,))
cursor.execute("select MAX(rowid) from [input33];")
rowid = cursor.fetchone()[0]
conn.close()
return rowid

Python and sqlite trouble

I can't show the data from database sqlite in python.
connection = sqlite3.connect('db')
connection.cursor().execute('CREATE TABLE IF NOT EXISTS users ( \
id TEXT, \
name TEXT, \
avatar TEXT \
)')
# In cycle:
query = 'INSERT INTO users VALUES ("' + str(friend.id) + '", "' + friend.name + '", "' + friend.avatar +'" )'
print query
connection.cursor().execute(query)
connection.commit()
# After cycle
print connection.cursor().fetchall()
Sample output of query variable:
INSERT INTO users VALUES ("111", "Some Name", "http://avatar/path" )
In result, fetchall returns empty tuple. Why?
UPD
Forgotten code:
connection.cursor().execute('SELECT * FROM users')
connection.cursor().fetchall()
→
[]
INSERT does not return data. To get the data back out, you'll have to issue a SELECT statement.
import sqlite3
con = sqlite3.connect("db")
con.execute("create table users(id, name, avatar)")
con.execute("insert into users(id, name, avatar) values (?, ?, ?)", (friend.id, friend.name, friend.avatar))
con.commit()
for row in con.execute("select * from users")
print row
con.close()
Because the create table string as displayed is syntactically invalid Python, as is the insert into string.
Actually, the answer to your first question is: because you use different cursors.
connection.cursor() creates a new cursor in the connection you created before. fetchall() gives you the results of the query you executed before in that same cursor. I.e. what you did was this:
# After cycle
cursor1 = connection.cursor()
cursor1.execute('SELECT * FROM users')
cursor2 = connection.cursor()
cursor2.execute("")
cursor2.fetchall()
What you should have done was this:
# After cycle
cursor = connection.cursor()
cursor.execute('SELECT * FROM users')
print cursor.fetchall()

Categories

Resources