i want to find the value of 'vazn' (one column of sql table) where 'id' column is equal to f1.
the table name is "billse"
"vazn" & "id1" are the columns of this table...
"f1" is a variable
f1 is a variable as following:
f1=int(enter3.get())
enter3 is an entry.
i entered the variable in enter3 that is equal to one of the existing 'id's in the sql table('bills')
this is my code:
self.cur.execute("SELECT vazn FROM billse WHERE id1='f1'")
vaznp = self.cur.fetchall()
print(vaznp)
i get 'null' when it prints vaznp
Why?
Use a prepared statement:
self.cur.execute("SELECT vazn FROM billse WHERE id1=?", f1)
vaznp = self.cur.fetchall()
print(vaznp)
Your current query is literally being interpreted as this:
SELECT vazn FROM billse WHERE id1='f1'
In other words, you are comparing the id1 column against the string 'f1', not against the value contained in that variable. Prepared statements also free you from the worry of dealing with properly escaping strings in your queries.
Related
I create a table with primary key and autoincrement.
with open('RAND.xml', "rb") as f, sqlite3.connect("race.db") as connection:
c = connection.cursor()
c.execute(
"""CREATE TABLE IF NOT EXISTS race(RaceID INTEGER PRIMARY KEY AUTOINCREMENT,R_Number INT, R_KEY INT,\
R_NAME TEXT, R_AGE INT, R_DIST TEXT, R_CLASS, M_ID INT)""")
I want to then insert a tuple which of course has 1 less number than the total columns because the first is autoincrement.
sql_data = tuple(b)
c.executemany('insert into race values(?,?,?,?,?,?,?)', b)
How do I stop this error.
sqlite3.OperationalError: table race has 8 columns but 7 values were supplied
It's extremely bad practice to assume a specific ordering on the columns. Some DBA might come along and modify the table, breaking your SQL statements. Secondly, an autoincrement value will only be used if you don't specify a value for the field in your INSERT statement - if you give a value, that value will be stored in the new row.
If you amend the code to read
c.executemany('''insert into
race(R_number, R_KEY, R_NAME, R_AGE, R_DIST, R_CLASS, M_ID)
values(?,?,?,?,?,?,?)''',
sql_data)
you should find that everything works as expected.
From the SQLite documentation:
If the column-name list after table-name is omitted then the number of values inserted into each row must be the same as the number of columns in the table.
RaceID is a column in the table, so it is expected to be present when you're doing an INSERT without explicitly naming the columns. You can get the desired behavior (assign RaceID the next autoincrement value) by passing an SQLite NULL value in that column, which in Python is None:
sql_data = tuple((None,) + a for a in b)
c.executemany('insert into race values(?,?,?,?,?,?,?,?)', sql_data)
The above assumes b is a sequence of sequences of parameters for your executemany statement and attempts to prepend None to each sub-sequence. Modify as necessary for your code.
I wish to retrieve a single value from this database I have created. For example, The user will select a Name from a drop down box (these names correspond to the name column in the database). The name chosen will be stored in a variable called name_value. I would like to know how to search the database for the name in name_value AND return ONLY the other text in the next column called Scientific, into another variable called new_name. I hope I explained that well?
connection = sqlite3.connect("Cw.db")
crsr = connection.cursor()
crsr.execute("""CREATE TABLE Names(
Name text,
Scientific text)""")
Inserting these values: (There is more but its unnecessary to add them all)
connection = sqlite3.connect("Cw.db")
crsr = connection.cursor()
crsr.execute("""INSERT INTO Names (Name, Scientific)
VALUES
('Human', 'Homo Sapien');""")
The SELECT statement in SQL can be used to query for rows with specific values, and to specify the columns to be returned.
In your case, the code would look something like this
stmt = """\
SELECT Scientific
FROM Names
WHERE Name = ?
LIMIT 1
"""
name = 'Human'
crsr.execute(stmt, (name,))
new_name = crsr.fetchone()[0]
A few points to note:
we use a ? in the SELECT statement as a placeholder for the value that we are querying for
we set LIMIT 1 in the SELECT statement to ensure that at most only one row is returned, since you want to assign the result to a single variable.
the value(s) passed to crsr.execute must be a tuple, even if there is only one value
the return value of crsr.fetchone is a tuple, even though we are only fetching one column.
Say I have 100 different integers I want to store like a row with 100 columns.
I am trying it like this:
db = sqlite3.connect("test.db")
c = db.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS nums(
id INTEGER PRIMARY KEY,
''')
for i in range(100):
c.execute('''
ALTER TABLE nums
ADD ''' + 'column_' + i + '''INTEGER''')
db.commit()
Someone told me that when you are using numbers as column names you could probably do it a better way. But if I for example have a list with strings in python, and I want to loop through them and store every individual string in its own column, the approach would be the same, right?
However, this code runs without errors for me, but no new table is created, how come?
Your ALTER statement is incorrect as it's missing the COLUMN after ADD. You can use the following:
for i in range(100):
c.execute(f'ALTER TABLE nums ADD COLUMN column_{i} INTEGER')
I have created a script that finds the last value in the first row of my database
import sqlite3
global SerialNum
conn = sqlite3.connect("MyFirstDB.db")
conn.text_factory = str
c = conn.cursor()
SerialNum = c.execute('select Serial from BI4000 where Serial in (Select max(Serial) from BI4000)')
print SerialNum
conn.commtt()
conn.close()
the program prints the result
[('00003',)]
which is the last result in the current database, all the data that will be entered into the final database will be serial numbers and so it will be in order.
My question is can I remove all the quotations/brackets/comma as I wish to asign this value to a variable.
The program that I wish to make is a testing system that adds new entries to the database, I wish to check what the last entry is in the database so the system can continue the entries from that point.
The result of the query you execute is being represented as a Python list of Python tuples.
The tuples contained in the list represent the rows returned by your query.
Each value contained in a tuple represents the corresponding field, of that specific row, in the order you selected it (in your case you selected just one field, so each tuple has only one value).
Long story short: your_variable = SerialNum[0][0]
If you want to retrieve just one column from one row, use:
c.execute('select Serial from BI4000 where Serial in (Select max(Serial) from BI4000)')
result = c.fetchone()
if result: # first row returned?
print result[0] # first column
Your query could be simplified to:
c.execute('Select max(Serial) from BI4000')
I have a table in SQLite3 database (using Python), Tweet Table (TwTbl) that has some values in the column geo_id. Most of the values in this column are NULL\None. I want to replace/update all NULLS in the geo_id column of TwTbl by a number 999. I am not sure about the syntax. I am trying the following query, but I am getting an error ("No such Column: None")
c.execute("update TwTbl SET geo_id = 999 where geo_id = None").fetchall()
I even tried using Null instead of None, that did not give any errors but did not do any update.
Any help will be appreciated.
As an answer, so that you can accept it if you're inclined.
You need Is Null instead of = Null. Null is a special value that's indeterminate, and neither equal nor non-equal in most database implementations.