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.
Related
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.
My Database
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
# c.execute('''CREATE TABLE Karteikarten
# ([Frage] text, [Antwort] text)''')
F1 = input("Frage: ") A1 = input("Antwort: ")
c.execute('INSERT INTO Karteikarten Values ( ?, ?)', (F1, A1,))
# c.execute('SELECT * FROM Karteikarten')
# print(c.fetchall())
conn.commit()
conn.close()
Now to my question. How can I take the selected input from the database and print it out? I want to compare it with an input from a user later.
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
print(DBF1)
conn.commit()
conn.close()
If all you want to do is fetch output from the database, then you'd use
foo = c.fetchone()
or
foo = c.fetchall()
to store the output from the database into a variable
You would then print(foo)
IE:
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
DBF1 = c.fetchone() # or c.fetchall()
print(DBF1)
conn.commit()
conn.close()
Just fetch your result before the print statement.
Change this:
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
to this:
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1').fetchall()
and print(DBF1) will give you the desired output as a list of tuples
I'm trying to "SELECT" a value from Db and add this value to another variable, but when I execute this I get this error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' "
id = input("Digite o id do cartão: ")
cash = int(input("Digite o o valor a ser creditado: "))
dia = 3
sql = 'SELECT saldo FROM carteira where idcartao = ?'
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
row = c.fetchone()
soma = (row) + (cash)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id))
connection.commit()
selectbanco()
THIS IS MY COMPLETE CODE
import sqlite3
connection = sqlite3.connect('clientes.db')
c = connection.cursor()
#criação de tabela
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS carteira (idcartao REAL, saldo REAL, data text)')
create_table()
#variaveis
id = input("Digite o id do cartão: ")
cash = int(input("Digite o o valor a ser creditado: "))
dia = 3
sql = 'SELECT saldo FROM carteira where idcartao = ?'
#SELECT E RETORNAR VALOR
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
row = c.fetchone()
##soma = (row + cash)
##print(soma)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (cash, id))
connection.commit()
selectbanco()
#leitura do banco
def read_data(wordUsed):
for row in c.execute(sql, (wordUsed,)):
print (row)
read_data(id)
connection.close()
You've got two issues here.
The first is that you exhaust your generator by calling row = c.fetchone() twice, without re-executing the query. You can only iterate through your cursor once for each query result; after that, you will need to re-run the query to "refresh" the data and be able to iterate again.
Second, fetchone() will actually return None if you get no matches. This is in contrast to fetchall() that will instead return an empty list ([]) in the case of no matches.
This quick example should illustrate this behaviour:
import sqlite3
# Create a fake database
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS some_table(
something TEXT
)""")
c.execute(""" INSERT INTO some_table VALUES('hello') """)
c.execute("SELECT * FROM some_table")
# We get a match and this will print '(hello,)'
data = c.fetchone()
print(data)
data = c.fetchone()
# If we don't execute the query again but try to use the exhausted generator
# then we'll also get None
print(data)
c.execute("SELECT * FROM some_table WHERE something = 'bye'")
# This will print 'None' because fetchone() didn't get a result
data = c.fetchone()
print(data)
c.execute("SELECT * FROM some_table WHERE something = 'bye'")
# This will print an empty list because fetchall() didn't get a result
data = c.fetchall()
print(data)
c.close()
conn.close()
Even though None and [] are different, they are still falsey so, in the context of your question, you can still convert either response to an integer:
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""create table if not exists some_table(
something TEXT
)""")
c.execute(""" INSERT INTO some_table VALUES('hello') """)
# Get back None or an integer
c.execute(""" SELECT * FROM some_table WHERE something = ?""", ('bye', ))
data = c.fetchone() or 1 # This is where you return an integer instead of None
print(data)
c.close()
conn.close()
I've picked an integer value of 1, maybe you want 0, I'm not sure. The thing to note, though, is that there's two avenues for you to get None or falsey data here, and you're treating them both the same, which isn't great for clarity of code.
You are fetching row twice. You need to remove the second fetch to receive the row.
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
soma = (row) + (cash)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id))
connection.commit()
selectbanco()
The variable gets overwritten because you do not specify a command to execute before fetching (the second time), hence the NoneType.
I'm not sure why I get this error when I test this function. Can anyone please help me fix this?
time_file.readlines()
builtins.ValueError: I/O operation on closed file.
I want to create a table for the time and insert all the values listed below, like idx, date, start, end, duration into the table.
def create_time_table(db, time_file):
'''Time Table should be ID,Date,Start,End,Duration
'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Time''')
# create the table
cur.execute('''CREATE TABLE TIME(idTEXT, DateTEXT, StartTEXT, EndTEXT,
DurationTEXT)''')
# insert the rows
time_file.readlines()
for line in time_file:
data = line.split(',')
idx = data[0]
date = data[1]
start = data[2]
end = data[3]
duration = data[4]
cur.execute('''INSERT INTO TIME VALUES(?, ?, ?, ?, ?)''',(idx, date, start, end, duration))
if __name__ == '__main__':
file2 = open('time.csv', 'r')
create_time_table("exams.db", file2)
file2.close()
#bigd since we are in the same class lol... here is the solution.. Your mistake is how you are reading the file, it should be time_file.readline(), if you do time_file.readlines(), using sqliteonline, the table would not appear.
def create_time_table(db, time_file):
'''Time Table should be ID,Date,Start,End,Duration
'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Time''')
# create the table
cur.execute('''CREATE TABLE Time(ID TEXT, Date TEXT, Start TEXT, End TEXT,
DurationTEXT)''')
# insert the rows
clock_file = open(time_file, 'r')
clock_file.readline()
for line in clock_file:
data = line.strip().split(',')
idx = data[0]
date = data[1]
start = data[2]
end = data[3]
duration = data[4]
cur.execute('''INSERT INTO TIME VALUES(?, ?, ?, ?, ?)''',(idx, date, start, end, duration))
# commit and close the cursor and connection
con.commit()
cur.close()
con.close()
## Under if __name__ == '__main__': ##
create_time_table('exams.db', 'time.csv')
I am trying to use Python to insert into MySQL database, but I have an auto-increment column (TeamID). I am using the lines below and it works like a charm. BUT I would like to not specify the TeamID in my Python script as it is an auto-increment
try:
cur.execute ("INSERT INTO teams values (%d, '%s', %d, '%s')" % (11,"Sevilla", 7, "Jorge Sampaoli"))
db.commit()
this works perfectly
How can I get rid of the first %d and 11 please? I want this value to be added automatically via the script
any help is very much appreciated
EDIT:
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="username", # your username
passwd="password", # your password
db="dbname") # name of the data base
cur = db.cursor()
try:
cur.execute ("INSERT INTO teams values ('%s', %d, '%s')" % ("Sevilla", 7, "Jorge Sampaoli"))
db.commit()
except Exception as e:
print("Rolling back")
print(e)
db.rollback()
db.close()
Issue is now resolved
I did specify the column names but didn't notice I need to use %s for all columns including int values. As below:
cur.execute("INSERT INTO teams (TeamName, CountryID, TeamManager) values (%s,%s,%s)", ('Everton', 1, 'Ronald Koeman'))
Try
INSERT INTO teams (name, numb, player) VALUES ('%s', %d, '%s')
I.e.explicitly list columns.
Also PLEASE don't do it like this -- instead of doing '%s' you really need to use prepared statements,I think in Python it is something like:
cursor.execute("INSERT INTO teams (name, numb, player) VALUES (%s, %d, %s)", ['Sevilla', 7, 'John Smith'])
Read up on SQL injections.
import sqlite3
def insert_data(lVideoList, gate_id):
connection = sqlite3.connect('db.sqlite',
detect_types=sqlite3.PARSE_DECLTYPES |
sqlite3.PARSE_COLNAMES)
cursor = connection.cursor()
success = 200
# gateid = 1
default_value = 0
for gate_id in range(no_of_gate):
gate_id = i+1
for videofilename in lVideoList:
print("videofilename: ", videofilename)
insert_query = ("INSERT INTO dailyfootfall(csv_name, video_download, processed, footfall, send_status, "
"male_footfall, send_status_male, female_footfall, send_status_female, gate_id,outsiders, send_status_outsiders) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)")
cursor.execute(insert_query,[videofilename, success, success, default_value, success, default_value,
success, default_value, success, gate_id, default_value, success])
print("Data Inserted Successfully !")
connection.commit()
cursor.close()
connection.close()
if __name__ == "__main__":
lVideoList = getCompleteVideoList("2022_01_24", "10:00", "22:00")
no_of_gate = 3
insert_data (lVideoList, gate_id)
print("default_value inserted!!!!")