Variable Input not inserting into SQLite3 - python

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.

Related

How can I enter data into database by pressing the button with using python?

I'm setting up a project by using python language to take feedback from customers by pressing the button, my question about the code to enter the data into the database?
import mysql.connector
connector = mysql.connector.connect(host="host", user="user", passwd="password", database="DB")
cnx = connector.cursor()
cnx.execute("INSERT INTO ... VALUES (%s)", ('data'))
# Or execute a query just as always
#cnx.execute("INSERT INTO ... VALUES (...)")
connector.commit()
# If "SELECT * FROM ..." use next line to get the data
#result = cnx.fetchall()
cnx.close()
connector.close()

Python SQL Update Syntax Issues

Hello I was following Python MYSQL update statement and managed to produce this code for my programme's SQL Update with variables function:
def editInfo(start, userName):
newFavGenre = input("Enter your favourite genre")
newFavArtist = input("Enter your favourite artist")
## userName is a global variable
con = lite.connect(db)
cur = con.cursor()
cur.execute ("""
UPDATE users
SET favGenre=%s, favArtist=%s
WHERE username=%s
""", (newFavGenre, newFavArtist, userName))
results = cur.fetchall()
return result
mainmenu()
And keep expericiencing this error code:
sqlite3.OperationalError: near "%": syntax error
Any ideas where I am going wrong?
It appears the post you are looking at is for MySQL and I conjecture that you're using the sqlite3 python interface based on your error.
Looking at the sqlite3 docs...
cur.execute("""
UPDATE users
SET favGenre=%s, favArtist=%s
WHERE username=%s
""", (newFavGenre, newFavArtist, userName))
Should instead be
cur.execute("""
UPDATE users
SET favGenre=?, favArtist=?
WHERE username=?
""", (newFavGenre, newFavArtist, userName))
You could also use their named style which instead of taking a tuple takes a dictionary.
cur.execute("""
UPDATE users
SET favGenre=:genre, favArtist=:artist
WHERE username=:username
""", {'genre':newFavGenre, 'artist': newFavArtist, 'username':userName})

Python2.7 - SQLite3 library outputs error message "sqlite3.OperationalError: near "?": syntax error"

Code is follow. How to get replaced ? by value of variables [table, url]?
Expected SQL command is select * from OTHER_URL where url="http://a.com/a.jpg"
This SQL command occurs no error on the sqlite3 command line interface.
import sqlite3
from contextlib import closing
dbname = "ng.db"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS OTHER_URL (url TEXT)")
conn.commit()
table = "OTHER_URL"
url = "http://a.com/a.jpg"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute('select * from ? where url="?"', [table, url])
print c.fetchone()
There are two errors here. Firstly, you can't use parameter substitution for table names (or column names), only for values. You need to use string interpolation for anything else.
Secondly, you don't need quotes around the value parameter; the substitution will take care of that.
So:
c.execute('select * from {} where url=?'.format(table), [url])

PyMySQL assigning a variable to table name, in Python

I am using PyMySQL in Python 2.7. I have to create a function - where, given a table name, the query will find unique values of all the column names.
Since there are more than one tables involved, I do not want to hard-code table name. Now, a simpler query is like:
cursor.execute(" SELECT DISTINCT(`Trend`) AS `Trend` FROM `Table_1` ORDER BY `Trend` DESC ")
I want to do something like:
tab = 'Table_1'
cursor.execute(" SELECT DISTINCT(`Trend`) AS `Trend` FROM tab ORDER BY `Trend` DESC ")
I am getting the following error:
ProgrammingError: (1146, u"Table 'Table_1.tab' doesn't exist")
Can someone please help. TIA
Make sure the database you're using is correct,and use %s to format you sql statement.
DB_SCHEMA='test_db'
table_name='table1'
connection = pymysql.connect(host=DB_SERVER_IP,
port=3306,
db=DB_SCHEMA,
charset='UTF8',
cursorclass=pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
sql = "SELECT DISTINCT(`Trend`) AS `Trend` FROM `%s` ORDER BY `Trend` DESC"%(table_name)
cursor.execute(sql)
connection.commit()
except Exception as e:
print e
finally:
connection.close()
Hope this helps.

Python & PostgreSQL: Function to insert variable arg into table?

I am trying to do the code as follows to register a player with a given name, but I can't get the argument name to do anything… I thought that %s was the variable to insert a string into a database, but it doesn't seem to work.
import psycopg2
def registerPlayer(name):
"""Registers new player."""
db = psycopg2.connect("dbname=tournament")
c = db.cursor()
c.execute("insert into Players values (%s);")
db.commit()
db.close()
registerPlayer("Butter")
When I run it, I get the error message:
ProgrammingError: syntax error at or near "%"
LINE 1: insert into Players values (%s);
You haven't actually passed the parameter into the execute method.
c.execute("insert into Players values (%s);", (name,))

Categories