Python sqlcipher3 INSERTS don't persist [duplicate] - python

This question already has an answer here:
SQLite not saving data between uses
(1 answer)
Closed 6 months ago.
I'm exploring sqlcipher3 with python, and I find that after inserting some rows, then closing and re-opening the database, my table is empty. This problem doesn't appear when I use the sqlcipher command-line utility itself.
from sqlcipher3 import dbapi2 as sqlcipher
db = sqlcipher.connect('testing.db')
db.execute('pragma key="testing"')
db.execute("create table people (name text primary key)")
db.execute("insert into people (name) values ('charlie'), ('huey')")
print(db.execute('select * from people').fetchall())
# => [('charlie',), ('huey',)]
db.close()
db = sqlcipher.connect('testing.db')
db.execute('pragma key="testing"')
print(db.execute('select * from people').fetchall())
db.close()
# => []
What have I missed here?

You are supposed to commit your transaction before closing the connection otherwise your transaction is lost : https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.close

Related

Inserting data into MySQL DB using Python [duplicate]

This question already has an answer here:
Why isn't the 'insert' function adding rows using MySQLdb?
(1 answer)
Closed 5 years ago.
I want to insert data to Mysql database using python. Here is my code
def insert_db(time_spent):
global user_id
global total_time_spent
user = user_id
project = get_project_id()
timesingle = time_spent
timeall = total_time_spent
#connect to the database
connect_db = mysql.connector.connect(user='root',password='',host='127.0.0.1',database='python_test')
cursor = connect_db.cursor()
cursor.execute("INSERT INTO time (user_id,project_id,spent_time,total_time) VALUES (%s,%s,%s,%s)",(user,project,timesingle,timeall)) # insert new row to table
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
#close the cursor and database connection
cursor.close()
connect_db.close()
The problem is when I execute this function, even 'last insert row id' is showing the id, the data is not inserting to the database. I checked all the variables in this function and they are not empty.
How can I fix this issue
Everytime you modify data in your database you need to commit all the changes with.
connect_db.commit();
This is to ensure that you only save changes where no errors happened.
You need to commit to marks the end of a successful transaction.
connect_db.commit()
For further information: https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
Please ensure that you use connect_db.commit() after every insert/update or other such statements.

Check if sql table exists in python [duplicate]

This question already has answers here:
How to test if a table already exists?
(4 answers)
Closed 6 years ago.
I am making a python application for a voting system. I am using sqlite3 to create a database which is stored locally on the user's machine.
I need a way to check if a table exists or not because the tables need to get created on each user's database file when they run the application but if the application is run when the tables exist and I just have a statement creating the tables it will run an error because the table already exists.
Here is some simplified sample code
conn = sqlite3.connect('firefight')
c = conn.cursor()
if table 'info' exists:
#do nothing
else:
c.execute("CREATE TABLE info(PRIMARY KEY id int, username text, password text)")
I think there are two options here. First, SQLite has a statement which would create the table only if it does not exist:
CREATE TABLE IF NOT EXISTS info (PRIMARY KEY id int, username text, password text)
But if you want a more database generic way to handle this, you could simply execute a regular CREATE TABLE statement and then handle the exception in Python.
You can execute this SQL:
select count(*) from sqlite_master where type='table' and name='table name'
if you get 1, the table exists, otherwise not exists.

Python Script to Delete Data from SQLite DB [duplicate]

This question already has answers here:
Sqlite insert query not working with python?
(2 answers)
Closed 6 years ago.
I'm new to python and SQLite, so I apologize if this is a dumb question. I've written the code below to open up a database and delete the data in the STAGING_LIDs table. The script runs, but when I check the DB, the data is still there. Am I doing something wrong?
import sqlite3
import csv
conn = sqlite3.connect('C:\\SQLite\\Budget_Dev.db')
cur = conn.cursor()
#delete all table data
cur.execute("DELETE FROM STAGING_LIDs;")
I'm using bernie's answer in this question (the accepted answer) as a template.
I figured it out. I needed to add a line:
conn.commit()

MySQLdb : why does .commit() don't change the result of a query on another client? [duplicate]

This question already has answers here:
Python's MySqlDB not getting updated row
(2 answers)
MySQL-python connection does not see changes to database made on another connection even after change is committed
(2 answers)
Closed 7 years ago.
I'm using MySQLdb on two computers and connect it to the same MySQL database. This database contains a database named dbtest with a table test with 50 rows, defined as following :
CREATE TABLE test (
id int PRIMARY KEY AUTO_INCREMENT,
val varchar(255)
)
I use the interpreter in order to setup the problem :
# Run this on the 2 computers Python interpreter :
import MySQLdb
connection = MySQLdb.connect(host="<database hostname>", user="root", passwd="<root password>")
cursor = connection.cursor()
cursor.execute("USE dbtest")
print cursor.execute("SELECT * FROM test") # will print 50.
All right. The two connections are setup. Now let's add a row with the first client :
# Run this on computer 1 :
cursor.execute("INSERT INTO test (val) VALUES ('gosh stackoverflow is so good !')")
connection.commit()
print cursor.execute("SELECT * FROM test") # will print 51.
Sounds good, WireShark prints the 51 rows returned by the database. But with the computer 2...
# Run this on computer 2 :
print cursor.execute("SELECT * FROM test") # will print 50, expected 51 because of the insert.
Why do I have 50 lines here ? How to avoid this issue ?
Sorry if it's a duplicate, I probably didn't find the right keywords.
EDIT: If I reset the connection on computer 2, I have the 51 lines.

Python, MySQL and cursors that fetch maps [duplicate]

This question already has answers here:
Python: use mysqldb to import a MySQL table as a dictionary?
(5 answers)
Closed 9 years ago.
After executing a query statement on a MySQL database connection, I perform:
rows = cursor.fetchall()
This gives an array of arrays. I'd like to have an array of dictionaries, where each dictionary takes its keys from the requested column names of my table and associates the values from the table.
How do I do this?
Well, you forgot to mention which mysql library you're using.
If using oursql (which I recommend, it is certainly the best one), use oursql's DictCursor. Example:
conn = oursql.connect(...)
curs = conn.cursor(oursql.DictCursor)
If using MySQLdb (why?) Use MySQLdb's DictCursor. Example:
conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)
curs = conn.cursor()
Doing that will give you a cursor that returns dicts for each row. Remember to not have duplicate rownames in your query.

Categories