sqlite3 remove brackets from printed data - python

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

Related

retrieving a single value from sql table

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.

Create a new SQLite table in python with for-loop

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

How to solve Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied on Delete and Excutemany? [duplicate]

Say I have a list of following values:
listA = [1,2,3,4,5,6,7,8,9,10]
I want to put each value of this list in a column named formatteddate in my SQLite database using executemany command rather than loop through the entire list and inserting each value separately.
I know how to do it if I had multiple columns of data to insert. For instance, if I had to insert listA,listB,listC then I could create a tuple like (listA[i],listB[i],listC[i]). Is it possible to insert one list of values without a loop. Also assume the insert values are integers.
UPDATE:
Based on the answer provided I tried the following code:
def excutemanySQLCodewithTask(sqlcommand,task,databasefilename):
# create a database connection
conn = create_connection(databasefilename)
with conn:
cur = conn.cursor()
cur.executemany(sqlcommand,[(i,) for i in task])
return cur.lastrowid
tempStorage = [19750328, 19750330, 19750401, 19750402, 19750404, 19750406, 19751024, 19751025, 19751028, 19751030]
excutemanySQLCodewithTask("""UPDATE myTable SET formatteddate = (?) ;""",tempStorage,databasefilename)
It still takes too long (roughly 10 hours). I have 150,000 items in tempStorage. I tried INSERT INTO and that was slow as well. It seems like it isn't possible to make a list of tuple of integers.
As you say, you need a list of tuples. So you can do:
cursor.executemany("INSERT INTO my_table VALUES (?)", [(a,) for a in listA])

which column of sql table is equal to a variable

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.

How to get value from Cursor execution result Python

I have a sqllite database in which the field dad_mmsi is created without a type:
c.execute('''CREATE TABLE IF NOT EXISTS AIS_anoniem
(dad_mmsi, dad_navstatus......)'''')
when i fetch the top result;
c.execute('SELECT DISTINCT dad_mmsi FROM AIS')
print c.fetchall()[0]
it prints:
(u'456000001',)
which is not the same as what i put in, because it is converted to a tuple.
EDIT: since it is a tuple i need to access the index of the value i want:
print c.fetchall()[0][0] == '456000001'
gives me:
'true'
fetchall returns a list of rows, and each row is a list (tuple) of columns.
So this is correct.
Your query with DISTINCT does not return the top result, it returns all unique values.
To return only the first result, use
SELECT dad_mmsi FROM AIS LIMIT 1
(but you should add an ORDER BY clause to control which record you get).
To return only one row, use not fetchall but fetchone.

Categories