try to print some table is sqlite3 using python - python-3.x

hi I am a new in python i tried to create a new class that handle with sqlite3 in my read method i try to print some var but is does not print anything can you help me?
here is the code can you fix it and tell me what the problem is
class SQLite_class() :
file_name=''
table_sql_name =''
# con = sqlite3.connect(self.c)
def creat_file_name(self):
self.file_name = input("enter the SQL fille name !")
self.file_name = self.file_name+'.sqlite'
return self.file_name
def conncection(self):
conn = sqlite3.connect(self.file_name)
return conn
def creat_cursor(self):
conn = self.conncection()
cur = conn.cursor()
return cur
def del_table(self):
cur = self.creat_cursor()
cur.execute('DROP TABLE IF EXISTS '+self.table_sql)
def creat_table(self):
cur = self.creat_cursor()
#adding a new option (name of table of more we need to add some {} and use the format function)
cur.execute( '''CREATE TABLE IF NOT EXISTS {} (data TEXT, number INTEGER)'''.format(self.table_sql_name))
self.commiting()
def insrt(self):
cur = self.creat_cursor()
cur.execute('''INSERT INTO {} (data, number) VALUES (?, ?)'''.format(self.table_sql_name) ,('Thunderstruck', 20))
def close(self):
conn = self.conncection()
conn.close()
def commiting(self):
conn = self.conncection()
conn.commit()
def read(self):
cur = self.creat_cursor()
cur.execute('''SELECT data, number FROM {}'''.format(self.table_sql_name))
for row in cur: print(row)
test = SQLite_class()
test.creat_file_name()
test.table_sql_name = 'Track'
test.creat_table()
test.insrt()
test.commiting()
test.read()
test.commiting()
test.close()

This comment # con = sqlite3.connect(self.c) indicates you know what has to be done. I suspect when that didn't work, you went down the rabbit hole of creating connections everywhere. Program should make one db connection. Every time it makes a connection, it loses what came before.
It could declare conn = '', then call conncection() once (and remove it from the other methods; they'll probably need to take conn as an argument). It'll take some try, try again, but it will get you to a better place.
And don't forget to fetch the rows once the SELECT is executed.

Related

This name error keeps popping up despite me importing the relevant library- // cur = conn.cursor()// conn is not defined?

cur = conn.cursor() conn is not defined
I have imported psycopg2 and therefore, the conn module should be recognised.
Below is my script if needs be.
# Small script to show PostgreSQL and Pyscopg together
import psycopg2
connection_to_db = psycopg2.connect("dbname='XYZ' user='XYZ' host='localhost' password='XYZ'")
try:
if connection_to_db:
print("Logged in")
except:
print("I am unable to connect to the database")
cur = conn.cursor()
cur.execute("SELECT ** FROM weather ")
Conn is not defined here. Either change connection_to_db to be conn or define it as a context manager. A benefit of context managers is that you don't have to close the connection manually
with psycopg2.connect("dbname='XYZ' user='XYZ' host='localhost' password='XYZ'") as conn:
with conn.cursor() as cur:
cur.execute("SELECT ** FROM weather ")

how to run python/djanjo shell as a script

In a tutorial on django we create a simple table run migrations and then go into a shell with the command:
python manage.py shell
from there, in the shell we run the following:
from flights.models import Flight
f = Flight(origin="New York", destination="london", duration=415)
f.save()
I'm trying to figure out how to run these commands from a py file so I created test.py:
from flights.models import Flight
f=Flight(origin="New York",destination="London", duration=415)
f.save()
but get the error Models aren't loaded. How to resolve? I'm definitely a little confused. I am able to update the database from a web served page with the following in my views.py file:
from django.shortcuts import render
from flights.models import Flight
def index(request):
f=Flight(origin="New York",destination="London", duration=415)
f.save()
return render(request, "flights/index.html", {
})
What I am asking is how to update the database directly on the backend. Do I just use standard python sql commands? For instance:
import sqlite3
from sqlite3 import Error
import csv
def sql_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def sql_create(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def sql_insert(conn,sql,data,single):
cur=conn.cursor()
if single:
cur.execute(sql,data)
rowCount = cur.lastrowid
else:
cur.executemany(sql,data)
rowCount = cur.rowcount
conn.commit()
return(rowCount)
def sql_select(conn,sql,data):
cur = conn.cursor()
cur.execute(sql,data)
rows = cur.fetchall()
return rows
def sql_update(conn,sql,data):
cur = conn.cursor()
cur.execute(sql,data)
conn.commit()
def sql_delete(conn,sql,mydata):
print(mydata)
cur = conn.cursor()
cur.execute(sql,mydata)
conn.commit()
def main():
insert = False
db_file = r"/home/saltydog/Database/crud.db"
# create a database connection
conn = sql_connection(db_file)
# create tables
sql_create_price_table = """ CREATE TABLE IF NOT EXISTS prices (
ticker text NOT NULL,
ymd integer,
price real,
PRIMARY KEY(ticker,ymd)
); """
sql_create_price2_table = """ CREATE TABLE IF NOT EXISTS prices2 (
ticker text NOT NULL,
ymd integer,
price real,
PRIMARY KEY(ticker,ymd)
); """
if conn is not None:
# create projects table
sql_create(conn, sql_create_price_table)
sql_create(conn, sql_create_price2_table)
conn.commit()
else:
print("Error! cannot create the database connection.")
if(insert):
sql_insert_record = """insert into prices(ticker,ymd,price)
values(?, ?, ?)"""
cnt = 0
with open('ibm.txt') as f:
reader = csv.reader(f)
for row in reader:
ticker = row[0]
ymd = row[1]
price = row[2]
data = (ticker, ymd, price)
if cnt != 0:
rowid = sql_insert(conn,sql_insert_record,data,True)
print(rowid)
cnt+=1
sql_insert_records = """insert into prices2(ticker,ymd,price)
values(?, ?, ?)"""
data=[]
cnt=0
with open('ibm.txt') as f:
reader = csv.reader(f)
for row in reader:
ticker = row[0]
ymd = row[1]
price = row[2]
if cnt != 0:
data.append((ticker, ymd, price))
cnt+=1
rowid = sql_insert(conn,sql_insert_records,data,False)
print(rowid)
select_records = """select ticker,ymd,price from prices
where ticker = ?
group by price
order by price"""
data=('IBM', )
rows = sql_select(conn,select_records,data)
for row in rows:
print(row)
select_records = """select ticker,ymd,price from prices
where ticker = ?
and price > ?"""
data=('IBM',100.0)
rows = sql_select(conn,select_records,data)
for row in rows:
print(row)
select_records = """select ticker,ymd,price from prices
where ymd = ?"""
data=(19990527, )
rows = sql_select(conn,select_records,data)
for row in rows:
print(row)
sql_update_records = """update prices
set price = ?
where ymd = ?"""
data = (200.00,19990527)
sql_update(conn,sql_update_records,data)
sql_delete_record = """delete from prices where ymd = ?"""
mydata = (19990528, )
sql_delete(conn,sql_delete_record,mydata)
if __name__ == '__main__':
main()

Using same connection with multiple resolvers in graphene

I have a code like this,
# SWAMI KARUPPASWAMI THUNNAI
import jwt
import graphene
from flask import request
from auth.helper import medease_token
from database.get_connection import get_connection
from flask_graphql import GraphQLView
class CredentialInformation(graphene.ObjectType):
"""
graphene object type to get the personal information about the user
"""
country_code = graphene.String()
phone = graphene.String()
verified = graphene.Int()
#medease_token
def resolve_country_code(self, root):
customer_token = request.headers["x-access-token"]
decoded_token = jwt.decode(customer_token, verify=False)
customer_id = decoded_token["customer_id"]
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("select country_code from customer_credential where id=%s limit 1", (customer_id, ))
result = cursor.fetchone()
return result["country_code"]
finally:
cursor.close()
connection.close()
#medease_token
def resolve_phone(self, root):
customer_token = request.headers["x-access-token"]
decoded_token = jwt.decode(customer_token, verify=False)
customer_id = decoded_token["customer_id"]
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("select phone from customer_credential where id=%s limit 1", (customer_id, ))
result = cursor.fetchone()
return result["phone"]
finally:
cursor.close()
connection.close()
#medease_token
def resolve_verified(self, root):
customer_token = request.headers["x-access-token"]
decoded_token = jwt.decode(customer_token, verify=False)
customer_id = decoded_token["customer_id"]
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("select verified from customer_credential where id=%s limit 1", (customer_id,))
result = cursor.fetchone()
return result["verified"]
finally:
cursor.close()
connection.close()
def credential_information_wrapper():
return GraphQLView.as_view("graphql", schema=graphene.Schema(query=CredentialInformation))
which uses flask-graphql and graphene for Python graphql. The code works absolutely fine but I think I am missing something here because I need to open new connections in every resolver, and I need to write same query again so there is a data duplication, so is this the right way of doing or am I missing something?
Any help would be highly appreciated! Thank you in advance.
Opening a new connection on every query (resolver in this case) is okay. You could also set a connection pool to minimize the cost of opening connections.
Just curious, what database adapter or ORM are you using? Would be great if you could refactor the connection and cursor steps into a single function to call on every resolver and only have to pass the SQL query string.

Why I am not able to connect to the database

import lot_details, car_details
import numpy as np
import sqlite3
conn = sqlite3.connect('parkingLot.db')
c = conn.cursor()
class Parking(object):
"""
Parking class which has details about parking slots
as well as operation performed on parking are present here
"""
def __init__(self):
self.slots = {}
def create_parking_lot(self, no_of_slots):
try:
c.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
except Exception as ex:
print("Couldn't make a table in DB")
no_of_slots = int(no_of_slots)
if len(self.slots) > 0:
print ("Parking Lot already created")
return
if no_of_slots > 0:
for i in range(1, no_of_slots+1):
temp_slot = lot_details.PSlot(slot_no=i, available=True)
self.slots[i] = temp_slot
print ("Created a parking lot with {} slots" .format(no_of_slots))
else:
print ("Number of slots provided is incorrect.")
return
Using above code I am trying to create a database(which is successful) but now I am not able to create the Table inside it using the above command.
I tried doing it separately its working there. But, I am not able to create it using above code.
Depending on how and where you are creating the Parking object I suspect this could be a scoping issue, either pass the db connection into the constructor or just create it in the constructor itself. Code modified for brevity. The following works for me.
import sqlite3
class Parking(object):
def __init__(self):
self.slots = {}
self.conn = sqlite3.connect('parkingLot.db')
def create_parking_lot(self, no_of_slots):
try:
cur = self.conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
except Exception as ex:
print("Couldn't make a table in DB")
return
parking = Parking()
parking.create_parking_lot(5)

Tweepy to sqlite3

I'm trying to use Twitter's Streaming API to save tweets to a database using sqlite3. The problem is my database comes back empty. I'm using DB Browser for SQLIte to check the schema and the table and columns are there but no values for any column. Any thoughts?
#create sql table
conn = sqlite3.connect('twitter_one5.db')
c = conn.cursor()
c.execute('''CREATE TABLE tweets
(coordinates integer,
place text)''')
conn.commit()
conn.close()
# open connection
conn = sqlite3.connect('twitter_one5.db')
c = conn.cursor()
Create a class to handle inserting tweet info into database:
class Tweet():
# data from tweet
def __init__(self, coordinates, place):
self.coordinates = coordinates
self.place = place
# insert data from tweet into DB
def insertTweet(self):
c.execute("INSERT INTO tweets (coordinates, place) VALUES(?, ?)",
(self.coordinates, self.place))
conn.commit()
Create a tweet listener using the Streaming API:
class listener(tweepy.StreamListener):
def on_status(self, status):
tweet_data = Tweet(status.coordinates, status.place)
tweet_data.insertTweet()
print('inserted')
Create instance of listener and filter for keywords:
l = listener()
stream = tweepy.Stream(auth, l)
stream.filter(track=['twitter'])

Resources