SQL and Python - using a variable in an SQL statement - python

import sqlite3
conn = sqlite3.connect('troubleshooting.db')
cur = conn.cursor()
user = input("hello")
for row in cur.execute('SELECT user FROM problems WHERE user = %s'):
print(row)
My problem here is that the variable 'user' is only being read as text and not changing occurring to what I name it (user = input("hello")). How do I change it so it does read it as a variable (please keep it simple, I am a beginner when it comes to programming).
Thanks for helping out :)

Related

Variable Input not inserting into SQLite3

i'm a bit of an amateur IT Professional who has been getting to grips with Python and Django. This query is just for Python and SQLite3.
So I have the following code, which is meant to take an input from the user, and then pass it to a function I have created.
from dbadd import inputdetails
import sqlite3
conn = sqlite3.connect('torndata.db')
c = conn.cursor()
print('Enter Name')
u_name = str(input())
print('Enter Age')
u_age = int(input())
print('Enter Gender')
u_gender = str(input())
inputdetails(u_name, u_age, u_gender)
conn.close()
And this is the function it is calling:
import sqlite3
conn = sqlite3 . connect ( 'torndata.db' )
cursor = conn.cursor ()
def inputdetails(u_name,u_age,u_gender):
cursor.execute("""
INSERT INTO userdata(name, age, gender)
VALUES (?,?,?)
""", (u_name, u_age, u_gender))
conn.commit()
I get no errors when it runs, but when I run the following, it shows no data has been moved to the table I have specified.
c.execute("SELECT * FROM userdata")
print(c.fetchall())
conn.commit()
conn.close()
The database is already created within SQLite3 and the table has been set up, I can query it directly.
Bad indent. The commit statement is not part of the function.

How do you display information from a database in python?

I am new to Python and I am trying to make a flashcard script that retrieves the keyword and the definition from a database and then displays both on a flashcard using pyqt.
Does anyone know how to do this because I am having real trouble figuring it out.
So far, I have some pseudo code below.
Function loadFlashcards(topic)
Import sqlite3
With sqlite3.connect (‘db_flashcards’) as db:
Cursor = db.cursor()
Sql = ‘SELECT * FROM tbl_flashcards’;
Cursor.execute(sql)
Result = cursor.fetchall()
for row in result:
print(“Defintion:” + str(row[2]
flip = input(“Press 1 to flip”)
if flip == “1”:
then print (“Keyword: +str[3])
else:
print(“Error”)
END for

Using Sqlite with WAL

I've been following Python documentation on the SQLite tutorial and I managed to create an Employee table and write to it.
import sqlite3
conn = sqlite3.connect('employee.db')
c = conn.cursor()
firstname = "Ann Marie"
lastname = "Smith"
email = "ams#cia.com"
employee = (email, firstname, lastname)
c.execute('INSERT INTO Employee Values (?,?,?)', employee)
conn.commit()
# Print the table contents
for row in c.execute("select * from Employee"):
print(row)
conn.close()
I've been reading about the Write-Ahead Logging, but I can't find a tutorial that explains how to implement it. Can someone provide an example?
I notice Firefox, which uses SQLite, locks the file in such a way that if you attempt to delete the sqlite file while using Firefox, it will fail saying "file is open or being used"(or something similar), how do I achieve this? I'm running Python under Windows 10.
conn = sqlite3.connect('app.db', isolation_level=None)
Set journal mode to WAL:
conn.execute('pragma journal_mode=wal')
Or another way (just show how to off wal mode)
cur = conn.cursor()
cur.execute('pragma journal_mode=DELETE')
The PRAGMA journal_mode documentation says:
If the journal mode could not be changed, the original journal mode is returned. […]
Note also that the journal_mode cannot be changed while a transaction is active.
So you have to ensure that the database library does not try to be clever and automatically starts a transaction.

Python : Accessing oracle database and updating it

I am accessing oracle database and trying to update it using python. Below is my code :
import cx_Oracle
import pandas as pd
import datetime
import numpy
import math
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
def update_output_table(customer_id_list,column_name,column_vlaue_list) :
num_rows_to_add = len(customer_id_list)
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
for i in range(0,num_rows_to_add,1) :
c.execute("""UPDATE output SET """+column_name+""" = %s WHERE customer_id = %s""" %(column_vlaue_list[i],customer_id_list[i]))
total_transaction_df = pd.read_sql("""select distinct b.customer_id,count(a.transaction_id) as total_transaction from transaction_fact a,customer_dim b where a.customer_id = b.CUSTOMER_ID group by b.CUSTOMER_ID""",conn)
# Update this details to the output table
update_output_table(list(total_transaction_df['CUSTOMER_ID']),'TOTAL_TRANSACTION',list(total_transaction_df['TOTAL_TRANSACTION']))
conn.close()
My program is getting executed completely but I don't see my database table getting updated. Can someone suggest where I am going wrong?
Note : I am a newbie.Sorry for asking silly doubts. Thanks in advance.
You're missing conn.commit() before conn.close():
Here you will find some info why you need it explicitely. Without commit your code is doing update then when closing connection all non-commited changes are rolled back so you see no changes in DB.
You can also set cx_Oracle.Connection.autocommit = 1 but this is not recommended way as you're loosing control over transactions.

using python 2.7 to query sqlite3 database and getting "sqlite3 operational error no such table"

My simple test code is listed below. I created the table already and can query it using the SQLite Manager add-in on Firefox so I know the table and data exist. When I run the query in python (and using the python shell) I get the no such table error
def TroyTest(self, acctno):
conn = sqlite3.connect('TroyData.db')
curs = conn.cursor()
v1 = curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
print v1
conn.close()
When you pass SQLite a non-existing path, it'll happily open a new database for you, instead of telling you that the file did not exist before. When you do that, it'll be empty and you'll instead get a "No such table" error.
You are using a relative path to the database, meaning it'll try to open the database in the current directory, and that is probably not where you think it is..
The remedy is to use an absolute path instead:
conn = sqlite3.connect('/full/path/to/TroyData.db')
You need to loop over the cursor to see results:
curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
for row in curs:
print row[0]
or call fetchone():
print curs.fetchone() # prints whole row tuple
The problem is the SQL statment. you must specify the db name and after the table name...
'''SELECT * FROM db_name.table_name WHERE acctno = ? '''

Categories