Why doesn't the record get saved in sqlite3? - python

I am using sqlite for the first time. I used Xammp before. Now I have a scene here. Each time I run the code below, records don't just get appended at the end of the table rather the table is created new and thus it's working just like a console.
Can any one tell me what I am doing wrong here?
import sqlite3
db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row
db.execute('drop table if exists test')
db.execute('create table test (t1 text,i1 text)')
db.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51'))
cursor = db.execute('select * from test')
for row in cursor:
print(row['t1'],row['i1'])

First, you need to execute commands on a cursor and not the connection itself. Second, you need to commit your transactions:
import sqlite3
db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row
cur = db.cursor() # getting a cursor
cur.execute('drop table if exists test')
cur.execute('create table test (t1 text,i1 text)')
db.commit() # commit the transaction, note commits are done
# at the connection, not on the cursor
cur.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51'))
db.commit()
cursor = cur.execute('select * from test')
for row in cursor:
print(row['t1'],row['i1'])
Please have a look at the documentation. This will help you once you start working with other databases in Python because they all follow the same API.

This line drops the old table:
db.execute('drop table if exists test')
And this one creates a new table:
db.execute('create table test (t1 text,i1 text)')
That should explain your problem. Remove these two lines and you'll be fine - But create the table first separately.

Related

how to drop all tables in sqlite3 using python?

i made a project which collects data from user and store it on different tables, the application has a delete function which the first option is to delete a specific table which is i already did and the second one is to delete all existing tables.
How can i drop all tables inside my database?
so this is my variables.
conn = sqlite3.connect('main.db')
cursor = conn.execute("DROP TABLE")
cursor.close()
How can i drop all tables inside my database?
According to sqlitetutorial.net
SQLite allows you to drop only one table at a time. To remove multiple
tables, you need to issue multiple DROP TABLE statements.
You can do it by querying all table names (https://www.sqlite.org/faq.html#q7)
Then you can use the result to delete the tables one by one
Here is the code, the function delete_all_tables does that
TABLE_PARAMETER = "{TABLE_PARAMETER}"
DROP_TABLE_SQL = f"DROP TABLE {TABLE_PARAMETER};"
GET_TABLES_SQL = "SELECT name FROM sqlite_schema WHERE type='table';"
def delete_all_tables(con):
tables = get_tables(con)
delete_tables(con, tables)
def get_tables(con):
cur = con.cursor()
cur.execute(GET_TABLES_SQL)
tables = cur.fetchall()
cur.close()
return tables
def delete_tables(con, tables):
cur = con.cursor()
for table, in tables:
sql = DROP_TABLE_SQL.replace(TABLE_PARAMETER, table)
cur.execute(sql)
cur.close()
SQLite3 code to issue multiple DROP TABLE statements based on TEMP_% name wildcard:
.output droptables.sql
SELECT "DROP TABLE """|| sqlite_master.name ||""";" FROM sqlite_master
WHERE type = "table" AND sqlite_master.name LIKE 'TEMP_%';
.read droptables.sql
Example result in .sql output file:
DROP TABLE "TEMP_table1";
DROP TABLE "TEMP_table2";
DROP TABLE "TEMP_table3";
...
Python3 to paste SQL into:
conn = sqlite3.connect(f"main.db")
conn.row_factory = sqlite3.Row
dbc = conn.cursor()
dbc.execute(
f"DROP TABLE 'TEMP_table1';"
)
conn.commit()

DB browser for sqlite does not work

I write a python code to create a table,but when I open DB browser for SQLite, it does not the table I have created, I am new to database, so can anyone tell me what is wrong with it ? Many thanks!
import sqlite3
conn = sqlite3.connect('test1.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Test''')
cur.execute('''
CREATE TABLE Test (azaz TEXT, count INTEGER)''')
cur.execute('''INSERT INTO Test (azaz, count)
VALUES ( 'aa', 1 )''' )
conn.commit()
conn.close()
image link:imgur.com/epfar.png
Your code is right and if you try:
import sqlite3
conn = sqlite3.connect('test1.sqlite')
row = conn.execute('SELECT * FROM Test').fetchone()
print("azaz=", row[0])
print("count=", row[1])
You will see this output:
('azaz=', u'aa')
('count=', 1)
So the table has been created and values has been inserted in the table.
I have just tested your code and it works flawlessly. I have used python-3.5 and DB Broswer for sqlite, tested on window 7 pro.

Exporting data from Entry widgets into SQL code

So I found this really useful piece of code earlier that created entry boxes and when they were created I could edit what was inside of them. The data that was loaded in was taken from an SQL table. Once I have made edits to the entry boxes, I want to submit the data to overwrite the data that had previously been in that sql record, as it it was being edited. The code I found was this:
for item in selectedetails:
entry = Entry(top2)
entry.insert(0, item)
entry.pack()
entries.append(entry)
I want it to be able to enter an sql code. I have tried this but it doesn't work. I think I am doing it wrong.
def submitedit():
for entry in entries:
print(entry.get())
db = sqlite3.connect('TestFile')
cursor = db.cursor()
cursor.execute('''UPDATE Table SET ID=?, Name=?, Desc=? WHERE ID=?''',
("?"," ?"," ?").format(entry.get()))
cursor.close()
db.commit()
db.close()
I have also tried this:
db = sqlite3.connect('TestFile')
cursor = db.cursor()
cursor.execute('''UPDATE Table SET ID=?, Name=?, Desc=? WHERE ID=?''',
(entry.get())
cursor.close()
db.commit()
db.close()
Thanks.
with sqlite3.connect('TestFile') as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "UPDATE Table Name=?, Desc=? WHERE ID=?"
cursor.execute(sql,(Name,Descr))
db.commit()
Note that the order that you put your values in cursor.execute line must match up to the order used in sql variable, otherwise the wrong values will be used at the wrong time. Also i have taken out set ID due to that being what you are searching off which im guessing is your primary key, in databases you should not edit the primary key. The primary key should be auto incremented as well.

Not able to insert into mysql database

I have just started using MySQLdb in python. I am able to create table but when I try to insert, no rows are inserted into the table and its shows that table is still empty.
import MySQLdb
db = MySQLdb.connect("localhost","root","shivam","test")
cursor = db.cursor()
s = "DROP TABLE IF EXISTS batting"
cursor.execute(s)
s = """create table batting (
name varchar(50) primary key,
matches integer(5),
innings integer(5),
runs integer(5),
highest integer(3),
strikerate integer(3),
hundreds integer(3),
fifties integer(3)
)"""
cursor.execute(s)
s = """insert into batting(name) values(
"shivam")"""
cursor.execute(s)
db.close()
Where I could be going wrong?
You forgot to commit your connection. Simply add:
cursor.execute(s)
db.commit()
Have a look at this. It explains why you need to commit

Nested queries using MySQLdb

I am trying to achieve the following using Python and the MySQLdb interface:
Read the contents of a table that has a few million rows.
Process and modify the output of every row.
Put the modified rows into another table.
It seems sensible to me to iterate over each row, process on-the-fly and then insert each new row into the new table on-the-fly.
This works:
import MySQLdb
import MySQLdb.cursors
conn=MySQLdb.connect(
host="somehost",user="someuser",
passwd="somepassword",db="somedb")
cursor1 = conn.cursor(MySQLdb.cursors.Cursor)
query1 = "SELECT * FROM table1"
cursor1.execute(query1)
cursor2 = conn.cursor(MySQLdb.cursors.Cursor)
for row in cursor1:
values = some_function(row)
query2 = "INSERT INTO table2 VALUES (%s, %s, %s)"
cursor2.execute(query2, values)
cursor2.close()
cursor1.close()
conn.commit()
conn.close()
But this is slow and memory-consuming since it's using a client-side cursor for the SELECT query. If I instead use a server-side cursor for the SELECT query:
cursor1 = conn.cursor(MySQLdb.cursors.SSCursor)
Then I get a 2014 error:
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x925d6ec>> ignored
So it doesn't seem to like starting another cursor while iterating over a server-side cursor. Which seems to leave me stuck with a very slow client-side iterator.
Any suggestions?
You need a seperate connection to the database, since the first connection is stuck with streaming the resultset, you can't run the insert query.
Try this:
import MySQLdb
import MySQLdb.cursors
conn=MySQLdb.connect(
host="somehost",user="someuser",
passwd="somepassword",db="somedb")
cursor1 = conn.cursor(MySQLdb.cursors.SSCursor)
query1 = "SELECT * FROM table1"
cursor1.execute(query1)
insertConn=MySQLdb.connect(
host="somehost",user="someuser",
passwd="somepassword",db="somedb")
cursor2 = inserConn.cursor(MySQLdb.cursors.Cursor)
for row in cursor1:
values = some_function(row)
query2 = "INSERT INTO table2 VALUES (%s, %s, %s)"
cursor2.execute(query2, values)
cursor2.close()
cursor1.close()
conn.commit()
conn.close()
insertConn.commit()
insertConn.close()

Categories