How can I open a db.sqlite3 file and have a look at its content? - sqlite

I don't know how to open a db.sqlite3 file in reader-friendly way.
I hope the data in it would be shown in tables

Upload your file here and get the tabulated result:
http://inloop.github.io/sqlite-viewer/
OR run a Python script like below
def create_connection(db_file):
""" create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None
try:
conn = sqlite3.connect(db_file) except Error as e:
print(e) return conn
def select_all_tasks(conn):
""" Query all rows in the tasks table :param conn: the Connection object :return: """
cur = conn.cursor()
cur.execute("SELECT * FROM tasks") rows = cur.fetchall() for row in rows: print(row)

Related

SQLlite: Why is the insert SQL statement not updating the table in the database?

I have a Python Pysimplegui form that is connecting to a SQL Lite database.
The function to create and update a table called fitness_class is:
def createFitnessClassTable(conn):
'''
'''
SQL = """CREATE TABLE IF NOT EXISTS fitness_class (
fitness_class_id integer PRIMARY KEY,
fitness_class_name text NOT NULL,
date_and_time text NOT NULL
);"""
sql_create = """INSERT OR IGNORE INTO fitness_class(fitness_class_id,fitness_class_name,date_and_time)
VALUES(?,?,?)"""
data = [
(1, 'Cardio', 'Thursday 35pm'),
(2, 'Pilates', 'Friday 911am'),
(3, 'Spin', 'Monday 2 4pm')
]
try:
c = conn.cursor()
c.execute(SQL)
c.close()
connection = conn.cursor()
connection.executemany(sql_create, data)
connection.close()
except Error as e:
# print(e)
sg.Popup(e)
return False
return True
When the function is called, this is creating the table and I am not getting any error messages. However, this is not saving the data (from the insert statement) either.
These are the rows related to calling the function
#!/usr/bin/python
import os
import PySimpleGUI as sg
from tkinter import *
import re
import sys
import PySimpleGUI as sg
import sqlite3
sys.path.append(os.path.dirname(__file__))
conn = dbconnect()
createFitnessClassTable(conn=conn)
conn.commit
conn.close()
I am confused because I have a similar function to create another table which is working correctly (i.e. creating the table if it doesn't exist and populating it with the data):
def createMembershipTable(conn):
'''
'''
SQL = """
CREATE TABLE IF NOT EXISTS membership (
membership_type_id integer PRIMARY KEY,
membership_type text NOT NULL,
weekly_amount real NOT NULL
);"""
sql_create = """INSERT OR IGNORE INTO membership(membership_type_id,membership_type,weekly_amount)
VALUES(?,?,?)"""
data = [(1, 'Basic', 10.00),
(2, 'Regular', 15.00),
(3, 'Premium', 20.00)
]
try:
c = conn.cursor()
c.execute(SQL)
c.close()
connection = conn.cursor()
connection.executemany(sql_create, data)
connection.close()
except Error as e:
print(e)
return False
return True
The lines to call that function:
conn = dbconnect()
createMembershipTable(conn)
conn.commit()
conn.close()
What am I missing? Why would the function createMembershipTable work as expected though the function createFitnessClassTable not work when they are both almost identical?
Just after posting (and 3 hours later), I realized the issue:
It was missing parenthesis after the conn.commit() in the createFitnessClassTable function call.

Error with connectin to database using sqlite3 with python

When running following code I get error which I posted at the bottom of the post. I followed tutorial on creating databases from here.
These functions worked when creating previous databases though.
I am using jupyter notebook v 3.5.
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except sqlite3.Error as e:
print("Connection error: [%s]" % e)
return None
def create_table(conn, create_table_sql ):
try:
c = conn.cursor()
c.execute(create_table_sql)
except sqlite3.Error as e:
print("Connection error while creating table: [%s]" % e)
def sqlTables(db_file):
sql_create_synset_table = ''' CREATE TABLE IF NOT EXISTS table_data (
id TEXT NOT NULL,
status TEXT NOT NULL,
confidence_score INT NOT NULL,
); '''
conn = create_connection(db_file)
if conn is not None:
create_table(conn,sql_create_synset_table)
else:
print("Error! cannot create db conn.")
def upload_data(db_file):
sqlTables(db_file)
conn = create_connection(db_file)
cursor = conn.cursor()
with conn:
for i in range(len(id_list)):
s_id = id_list[i]
status = status_list[i]
conf = conf_list[i]
cursor.execute("INSERT INTO table_data(id, status, confidence_score) VALUES(?,?,?)"\
,(s_id, status, conf))
conn.commit()
upload_data("path/to/db/table.db")
Connection error while creating table: [near ")": syntax error]
---> 12 cursor.execute("INSERT INTO table_data(id, status, confidence_score) VALUES(?,?,?)" ,(sset_id, stus, conf))
OperationalError: no such table: table_data

Sqlite3 Do I have to attach a database on every connection?

The following piece of code creates two databases:
import sqlite3
db = 'brazil'
conn = sqlite3.connect(db+'.db')
c = conn.cursor()
qCreate = """
CREATE TABLE states
(zip_id numeric NOT NULL,
state_name text NOT NULL,
CONSTRAINT pk_brazil
PRIMARY KEY (zip_id) """
c.execute(qCreate)
conn.commit()
conn.close()
db = 'city'
conn = sqlite3.connect(db+'.db')
c = conn.cursor()
qCreate = """CREATE TABLE rio_de_janeiro
(zip_id numeric NOT NULL,
beach_name text NOT NULL,
CONSTRAINT pk_rio
PRIMARY KEY (zip_id)
"""
c.execute(qCreate)
conn.commit()
conn.close()
The following piece of code attaches the database RIO to the database BRAZIL and prints all the databases (Rio and Brazil).
db = 'brazil'
conn = sqlite3.connect(db+'.db')
c = conn.cursor()
qCreate = """ATTACH DATABASE ? AS competition """
c.execute(qCreate, ('rio.db',))
c.execute("PRAGMA database_list")
data = c.fetchall()
print data
conn.commit()
conn.close()
However the following piece of code prints only Brazil database:
db = 'brazil'
conn = sqlite3.connect(db+'.db')
c = conn.cursor()
c.execute("PRAGMA database_list")
data = c.fetchall()
print data
conn.commit()
conn.close()
The attached database is no longer attached.
The sqlite3 documentation hints on these lines:
The ATTACH DATABASE statement adds another database file to the current database connection.
Do I have to attach the database every time?
I planed to use attached databases for schemas, but maybe I should try something else?
I am using python in Pythonista App in iOS
Almost all settings you can change in SQLite apply only to the current connection, i.e., are not saved in the database file.
So you have to re-ATTACH any databases whenever you have re-opened the main database.
Using attached databases makes sense only if you must use multiple database files due to some external constraint. In most cases, you should use only a single database.
SQLite does not have schemas. If you want to emulate them with attached databases, you have to live with the limitations of that approach.

sqlite database OK but jdbc reports database disk image is malformed

I have a newly created sqlite database, it is somewhat large: about 6.3GB. I have no problems using it through the sqlite command line tool. When I try to connect using the JDBC (groovy script) I got the exception:
Caught: java.sql.SQLException: [SQLITE_CORRUPT] The database disk image
is malformed (database disk image is malformed)
I then ran from the sqlite command line tool:
pragma integrity_check;
which reported back with: ok
I tried out the groovy script against a new database with a single table with a single row and it appears to work.
Any suggestions?
using:
jdk1.7.0_60
groovy-2.3.4
sqlite-jdbc-3.7.2
groovy script:
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
println("hello world")
Class.forName("org.sqlite.JDBC")
String dbFile =
"/opt/no_backup/text_analytics/db/options.sqlite3" //large database - exception
// "/opt/no_backup/text_analytics/test/test.db" //small database - works
Connection conn = DriverManager.getConnection("jdbc:sqlite:$dbFile")
String query =
// "select count(*) from test" //small database - works
"select count(*) from bb_options where underlyingSymbol='GE'" //large database - fails
ResultSet rs = conn.createStatement().executeQuery(query)
while(rs.next()) {
println(rs.getInt(1))
}
conn.close()

How to use sqlalchemy to select data from a database?

I have two sqlalchemy scripts, one that creates a database and a few tables and another that selects data from them.
create_database.py
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey, select
engine = create_engine('sqlite:///test.db', echo=True)
metadata = MetaData()
addresses = Table ('addresses', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', None, ForeignKey('users.id')),
Column('email_addresses', String, nullable=False)
)
users = Table ('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('fullname', String),
)
metadata.create_all(engine)
select.py
from sqlalchemy import create_engine, select
engine = create_engine('sqlite:///test.db', echo=True)
conn = engine.connect()
s = select([users])
result = conn.execute(s)
I am able to run the create_database.py script but when I run the select.py script I get the following error
$ python select.py
Traceback (most recent call last):
File "select.py", line 5, in <module>
s = select([users])
I am able to run the select statement from within the create_database.py by appending the following to create_database.py
conn = engine.connect()
s = select([users])
result = conn.execute(s)
How can I run the select statements from a separate script than create_database.py
The script select.py does not see users and addresses defined in create_database.py. Import them in select.py before using them.
In select.py:
from create_database import users, addresses
## Do something with users and addresses

Resources