Error with connectin to database using sqlite3 with python - sqlite

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

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.

How to test a flask app using pytest to get the coverage rate up

Currently this is my app.py files
# imports - standard imports
import json
import os
import sqlite3
# imports - third party imports
from flask import Flask, Response, jsonify, redirect
from flask import render_template as render
from flask import request, url_for
DATABASE_NAME = "inventory.sqlite"
# setting up Flask instance
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY="dev",
DATABASE=os.path.join(app.instance_path, "database", DATABASE_NAME),
)
# listing views
link = {x: x for x in ["location", "product", "movement"]}
link["index"] = "/"
def init_database():
db = sqlite3.connect(DATABASE_NAME)
cursor = db.cursor()
# initialize page content
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS
products(prod_id INTEGER PRIMARY KEY AUTOINCREMENT,
prod_name TEXT UNIQUE NOT NULL,
prod_quantity INTEGER NOT NULL,
unallocated_quantity INTEGER);
"""
)
cursor.execute(
"""
CREATE TRIGGER IF NOT EXISTS default_prod_qty_to_unalloc_qty
AFTER INSERT ON products
FOR EACH ROW
WHEN NEW.unallocated_quantity IS NULL
BEGIN
UPDATE products SET unallocated_quantity = NEW.prod_quantity WHERE rowid = NEW.rowid;
END;
"""
)
# initialize page content
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS location(loc_id INTEGER PRIMARY KEY AUTOINCREMENT,
loc_name TEXT UNIQUE NOT NULL);
"""
)
# initialize page content
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS logistics(trans_id INTEGER PRIMARY KEY AUTOINCREMENT,
prod_id INTEGER NOT NULL,
from_loc_id INTEGER NULL,
to_loc_id INTEGER NULL,
prod_quantity INTEGER NOT NULL,
trans_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(prod_id) REFERENCES products(prod_id),
FOREIGN KEY(from_loc_id) REFERENCES location(loc_id),
FOREIGN KEY(to_loc_id) REFERENCES location(loc_id));
"""
)
db.commit()
#app.route("/product", methods=["POST", "GET"])
def product() -> Response | str:
init_database()
msg = None
db = sqlite3.connect(DATABASE_NAME)
cursor = db.cursor()
cursor.execute("SELECT * FROM products")
products = cursor.fetchall()
if request.method == "POST":
prod_name = request.form["prod_name"]
quantity = request.form["prod_quantity"]
transaction_allowed = False
if prod_name not in ["", " ", None] and quantity not in ["", " ", None]:
transaction_allowed = True
if transaction_allowed:
try:
cursor.execute(
"INSERT INTO products (prod_name, prod_quantity) VALUES (?, ?)",
(prod_name, quantity),
)
db.commit()
except sqlite3.Error as e:
msg = f"An error occurred: {e.args[0]}"
else:
msg = f"{prod_name} added successfully"
if msg:
print(msg)
return redirect(url_for("product"))
return render(
"product.html",
link=link,
products=products,
transaction_message=msg,
title="Products Log",
)
and this is my test function in test_product.py. I want to test my function to get my coverage on sonarcloud to be 100%. And the pytest function below seems to have no use. I must say I am very beginner to it and I am still learning.
import requests
import app
import pytest
ENDPOINT = "http://127.0.0.1:5000/product"
app.init_database()
def test_product_GET():
response = requests.get(ENDPOINT)
assert response.status_code == 200
# assert "Products Log" in response.text
#pytest.fixture()
def test_product_POST_valid():
response = requests.post(ENDPOINT, data={"prod_name": "product1", "prod_quantity": "10"}, allow_redirects=True)
assert response.status_code == 200
# assert "product1 added successfully" in response.text
#pytest.fixture()
def test_product_POST_invalid():
response = requests.post(ENDPOINT, data={"prod_name": "", "prod_quantity": ""}, allow_redirects=True)
assert response.status_code == 200
# assert "An error occurred" in response.text
I am not sure of how to make this work wihtout using request and it does have 0% coverage and I want to test this code in sonarcloud

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

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)

Error while trying to delete a sqlite table in haskell

I have a problem when trying to delete a complete table in sqlite, could someone help me?
code:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Database.SQLite.Simple
import Database.SQLite.Simple.FromRow
data TestField = TestField Int String deriving (Show)
instance FromRow TestField where
fromRow = TestField <$> field <*> field
main :: IO()
main = do
conn <- open "db1.sqlite"
execute conn "DROP TABLE tabela"
close conn
Returning the error:
delete.hs:14:3: error:
• Couldn't match expected type ‘IO a0’
with actual type ‘q0 -> IO ()’
• Probable cause: ‘execute’ is applied to too few arguments
In a stmt of a 'do' block: execute conn "DROP TABLE tabela"
In the expression:
do { conn <- open "db1.sqlite";
execute conn "DROP TABLE tabela";
close conn }
In an equation for ‘main’:
main
= do { conn <- open "db1.sqlite";
execute conn "DROP TABLE tabela";
close conn }
Failed, modules loaded: none.
execute requires a query parameter. From the haddocks:
execute :: ToRow q => Connection -> Query -> q -> IO ()
Try
execute conn "DROP TABLE tabela" ()

ERROR at line : PL/SQL: SQL Statement ignored. while creating/replacing package body

I am using Visual Studio 2010 asp.net 4.5 Oracle 10.2.0.1.
This is my repository code for checking user credentials:
using (OracleConnection oracleConnection = new BaseRepository().Connection)
{
oracleConnection.Open();
OracleCommand command = new OracleCommand("PACKAGE_ACCOUNT.USP_GET_USER_BY_CREDENTIALS", oracleConnection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add("SP_CURSOR", OracleDbType.RefCursor, System.Data.ParameterDirection.Output);
command.Parameters.Add("SP_LOGIN_NAME", OracleDbType.Varchar2, 50, loginName, System.Data.ParameterDirection.Input);
command.Parameters.Add("SP_LOGIN_PASSWORD", OracleDbType.Varchar2, 50, Security.EncryptText(loginPassword), System.Data.ParameterDirection.Input);
Mapper.CreateMap<IDataReader, ApplicationUser>();
dataReader = command.ExecuteReader(); // exception arises here.
List<ApplicationUser> lstUsers = Mapper.Map<List<ApplicationUser>>(dataReader);
return lstUsers.FirstOrDefault();
}
this is package specification:
CREATE OR REPLACE PACKAGE PACKAGE_ACCOUNT
AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE USP_GET_USER_BY_CREDENTIALS(SP_CURSOR OUT T_CURSOR, SP_LOGIN_NAME IN VARCHAR2, SP_LOGIN_PASSWORD IN VARCHAR2);
END PACKAGE_ACCOUNT;
/
this is my package body:
CREATE OR REPLACE PACKAGE BODY PACKAGE_ACCOUNT
AS
PROCEDURE USP_GET_USER_BY_CREDENTIALS(SP_CURSOR OUT T_CURSOR, SP_LOGIN_NAME IN VARCHAR2, SP_LOGIN_PASSWORD IN VARCHAR2)
IS
BEGIN
OPEN SP_CURSOR FOR
SELECT "ApplicationUser".*, ora_rowscn as TimeStamp
FROM "ApplicationUser"
WHERE "LoginName" = SP_LOGIN_NAME
AND "LoginPassword" = SP_LOGIN_PASSWORD
AND "IsDeleted" = 'N';
END USP_GET_USER_BY_CREDENTIALS;
END PACKAGE_ACCOUNT;
/
Exception is :
ORA-04063: package body "OPTIMUS_USER.PACKAGE_ACCOUNT" has errors
ORA-06508: PL/SQL: could not find program unit being called: "OPTIMUS_USER.PACKAGE_ACCOUNT"
ORA-06512: at line 1
I have no idea where the problem is.
While running the package body script in oracle home page. It gives error:
ERROR at line 5: PL/SQL: SQL Statement ignored.
Please check OPTIMUS_USER schema does the schema contains the package PACKAGE_ACCOUNT or the PACKAGE_ACCOUNT account schema belongs to any other schema.

Resources