python postgresql select user input - python

I'm having a problem and I think that I'm missing something very basic. I'm kind of a noob if it comes to programming but I guess I learn quick. I'm trying to make a Python script that asks for user input and then performs Postgresql SELECT. Then, the outcome of SELECT should be put into another script that uses SSH but I can't wrap my head around that SELECT query. There is a basic example of my code, if you have any tips I would appreciate greatly:
print('Diagnostic tool')
print('')
print('Please insert account ID:')
input()
try:
conn = psycopg2.connect("dbname='psql' user='user' host='localhost'
password='pasword'")
cur = conn.cursor()
cur.execute("SELECT * FROM exampletable WHERE acc_id = #userinput ")
cur.fetchall()
except:
print ("Could not establish connection to Database")
As shown above- how do I perform a query that uses SELECT WHERE table name is user input (acc_id)?

you can use format function on a string.
id = input("Please enter your id")
# id should be passed to format.
query = "SELECT * FROM exampletable WHERE acc_id = {} ".format(id)
try:
conn = psycopg2.connect("dbname='psql' user='user' host='localhost'
password='pasword'")
cur = conn.cursor()
cur.execute(query )
cur.fetchall()
except:
print ("Could not establish connection to Database")

You should pass the input as a parameter to the query. If the input string is saved in userInput you can do:
cur.execute("SELECT * FROM exampletable WHERE acc_id = %s", (userInput,))
Note: for input if your purpose is to take just the input without evaluationg as python code you should use the function raw_input().

Related

Creating a table based on input, if input doesnt exist in db file creates a table, if exists, writes ID to it

I'm trying to make a program in Python that requests an input and if the table in the DB exists, writes to it, and if it doesn't, creates it.
Here is the existing code:
connection = sqlite3.connect('AnimeScheduleSub.db')
cursor = connection.cursor()
anime_id = input('enter server id')
discord_user_id = int(input('Enter token'))
try:
cursor.execute("SELECT * FROM {}".format(anime_id))
results = cursor.fetchall()
print(results)
except:
command1 = f"""CREATE TABLE IF NOT EXISTS
{anime_id}(discord_user_id INTEGER)"""
cursor.execute(command1)
Basically, what it's doing (or what I'm trying to achieve) is the try loop is meant to check if the anime_id table exists. The except loop is meant to create the table if the try loop failed.
But it doesn't work, and I have no idea why. Any help would be much appreciated.
command1 = f"""CREATE TABLE IF NOT EXISTS
A{anime_id}(discord_user_id INTEGER)"""
Creating table name with just numbers are not supported by sql.
You should start with a letter and then use numbers.
You should "ask" the DB if the table is there or not.
Something like the below.
anime_id = input('enter server id')
SELECT name FROM sqlite_master WHERE type='table' AND name='{anime_id}';

"Insert into table values" does not send data

I am new in this and this is my first question. I hope you guys will help.
If my question format is wrong, feel free to comment on that also.
The code is pretty simple. I have DB connection, 2 functions - one for printing and another for choosing how many SQL queries I want to execute and input for those queries.
Idea is to enter a number(INT) of SQL queries - for example, 2 and then in another line user must enter 2 SQL queries.
After that, call_table function will print out current table status/situation/data.
For example - user wants to print out into console table data (table have 2 columns, [name][college], varchar type)
Insert a number of SQL queries you want to execute: 1
Insert SQL statement:
select * from student
('ivan', 'ino')
('nena', 'fer')
('tomislav', 'ino')
('marko', 'fer')
('tomislav', 'ino')
('marko', 'fer')
When I try to insert some values into the same table nothing happens with the table, data is not entered.
The query is 100% correct since I tested it in workbench, also I've tried to create another table from this program and the query was executed normally and the table was created.
I receive no errors.
Code is below:
import pymysql
db = pymysql.connect(host='localhost', user='root', passwd='123456', database='test')
mycursor = db.cursor()
def call_table(data_print):
for i in data_print:
print(i)
def sql_inputs(cursor):
container = []
no = int(input("Insert a number of SQL queries you want to execute: "))
for i in range(no):
container = [input("Insert SQL statement: \n").upper()]
for y in container:
cursor.execute(y)
sql_inputs(mycursor)
call_table(mycursor)
What am I doing wrong?
I tried even more complicated SQL queries but insert into the table is not working.
Thank you
Everything is good with the code, you're just missing cursor.commit()
By default cursor commit is false in python for insert queries.
cursor.execute(y)
cursor.commit()
and if you're done with queries
db.close()
You should append the queries to the container variable
import pymysql
db = pymysql.connect(host='localhost', user='root', passwd='123456', database='test')
mycursor = db.cursor()
def call_table(data_print):
for i in data_print:
print(i)
def sql_inputs(cursor):
container = []
no = int(input("Insert a number of SQL queries you want to execute: "))
for i in range(no):
container.append(input("Insert SQL statement: \n").upper())
for y in container:
cursor.execute(y)
sql_inputs(mycursor)
call_table(mycursor)
At the end of the program, I've added db.commit(), and everything works fine now.
import pymysql
db = pymysql.connect(host='localhost', user='root', passwd='45fa6cb2',
database='ivan')
mycursor = db.cursor()
def call_table(data_print):
for i in data_print:
print(i)
def sql_inputs(cursor):
container = []
no = int(input("Insert a number of SQL queries you want to execute: "))
for i in range(no):
container.append(input("Insert SQL statement: \n").upper())
for y in container:
cursor.execute(y)
sql_inputs(mycursor)
db.commit()
call_table(mycursor)

Python MySQL Statement output: 0 or 1

I am trying to get Information from my database, and print it, but unfortunately, Instead of Printing the Information from the Table, it just Prints 0 or 1.
Why does it do this?
Can someone please help me?
sql = ("SELECT code FROM testing WHERE email = ((%s))")
sql2 = a.execute(sql, (fullemail))
sqlusername = ("SELECT username FROM testing123 WHERE code = ((%s))")
username = a.execute(sqlusername, (sql2))
print("Test3")
print(username)
Thank you.
The execute() method just returns the number of impacted rows.
You must use .fetchall() or equivalent (e.g. .fetchone()...) DBAPI methods to get a resultset.
Also, using parentheses alone around a single value: (fullemail) will not be recognized as a tuple, you need to explicitly add a comma so Python will recognize this as a tuple: (fullemail, )
sql = ("SELECT code FROM testing WHERE email = %s")
a.execute(sql, (fullemail, ))
sql2 = a.fetchall()
print(sql2)
sqlusername = ("SELECT username FROM testing123 WHERE code = %s")
a.execute(sqlusername, (sql2[0][0], ))
username = a.fetchall()
print("Test3")
print(username)
Depending on which library you are using:
MySQLdb (python 2.7)
mysqlclient (MySQLdb for python3)
PyMySQL (pure Python)
You can also use a DictCursor to get your result set rows as dict instead of list. Usage is like:
from pymysql.cursors import DictCursor
import pymysql
db = pymysql.connect(host="", user="", passwd="", cursorclass=DictCursor)
with db.cursor() as cur:
cur.execute("SELECT ...")
results = cur.fetchall()
This will give you a list of dictionaries instead of a list of lists.

Python insert data into MySQL

I've encounter a problem when i try to insert values into mysql using python connector.
The problem is that i'm trying to pass an input as a value in mysql, but the input is added as name of the table instead of value of field. Can anyone let me now what am i doing wrong?
My code is:
import mysql.connector
from mysql.connector import errorcode
def main():
try:
connection= mysql.connector.connect(user='root',passwd='',host='localhost',port='3306', database='game_01')
print("Welcome")
name_of_char = input("Your name?: ")
con = connection.cursor()
con.execute("INSERT into charachter (name,intel,strenght,agil) values(%s,0,0,0)" % str(name_of_char))
con.execute("SELECT * FROM charachter")
for items in con:
print(items[1])
except mysql.connector.Error as err:
print(err)
else:
connection.close()
main()
Thanks.
P.S
The error is : 1054: Unknown column in 'field list'. I forgot to mention that in the post. It seems if i enter the tables attribute,it will work but won't add any value.
if you using MySQLdb driver , after execute the query that insert into database or update , you should use connection.commit() to complete saving operation.
try this:
con = connection.cursor()
con.execute("INSERT into `charachter` (`name`,`intel,`strenght`,`agil`) values('%s',0,0,0)" % str(name_of_char))
connection.commit()
if you use any other driver , you should set the auto_commit option true.
see this:
How can I insert data into a MySQL database?

Error while testing postgresql database with python

I wanted to start into using databases in python. I chose postgresql for the database "language". I already created several databases, but now I want simply to check if the database exists with python. For this I already read this answer: Checking if a postgresql table exists under python (and probably Psycopg2) and tried to use their solution:
import sys
import psycopg2
con = None
try:
con = psycopg2.connect(database="testdb", user="test", password="abcd")
cur = con.cursor()
cur.execute("SELECT exists(SELECT * from information_schema.testdb)")
ver = cur.fetchone()[0]
print ver
except psycopg2.DatabaseError, e:
print "Error %s" %e
sys.exit(1)
finally:
if con:
con.close()
But unfortunately, I only get the output
Error relation "information_schema.testdb" does not exist
LINE 1: SELECT exists(SELECT * from information_schema.testdb)
Am I doing something wrong, or did I miss something?
Your question confuses me a little, because you say you want to look to see if a database exists, but you look in the information_schema.tables view. That view would tell you if a table existed in the currently open database. If you want to check if a database exists, assuming you have access to the 'postgres' database, you could:
import sys
import psycopg2, psycopg2.extras
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
dbname = 'db_to_check_for_existance'
con = None
try:
con = psycopg2.connect(database="postgres", user="postgres")
cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("select * from pg_database where datname = %(dname)s", {'dname': dbname })
answer = cur.fetchall()
if len(answer) > 0:
print "Database {} exists".format(dbname)
else:
print "Database {} does NOT exist".format(dbname)
except Exception, e:
print "Error %s" %e
sys.exit(1)
finally:
if con:
con.close()
What is happening here is you are looking in the database tables called pg_database. The column 'datname' contains each of the database names. Your code would supply db_to_check_for_existance as the name of the database you want to check for existence. For example, you could replace that value with 'postgres' and you would get the 'exists' answer. If you replace the value with aardvark you would probably get the does NOT exist report.
If you're trying to see if a database exists:
curs.execute("SELECT exists(SELECT 1 from pg_catalog.pg_database where datname = %s)", ('mydb',))
It sounds like you may be confused by the difference between a database and a table.

Categories

Resources