How to check if a table exists using python? - python

I want to check whether the table exists or not before inserting the data.
This is what i have tried:
def checkTables(tablename):
stmt = "SHOW TABLES LIKE %s"%tablename
cursor.execute(stmt)
result = cursor.fetchone()
return result
But it gives me error saying:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ctg_payload3' at line 1

Maybe it is not the best way.
As for my opinion, I will show tables;, then search the result.
And, I you cannot execute show tables like tablename;, no syntax like that.
edit 1
If you must do it in sql, use
show table status like 'table_name';
' is needed for this sql.

Try this query string :SHOW TABLES WHERE Tables_in_mydb LIKE '%tablename%' or
this one
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'my_database_name'
AND table_name LIKE '%tablename%'
Good luck

Try this.
def checkTables(tablename):
stmt = "SHOW TABLES LIKE '%s' "% ('%'+str(tablename)+'%')
cursor.execute(stmt)
result = cursor.fetchone()
return result

Related

Unable to execute "DESCRIBE ARADMIN.EPM_TechnicianInformation" in python jupyter notebook with cxOracle

When I execute query "DESCRIBE ARADMIN.EPM_TechnicianInformation" like below:
connection = cx_Oracle.connect(user=username, password=userpwd, dsn=dsn, encoding="UTF-8")
cursor = connection.cursor()
results = cursor.execute(" DESCRIBE ARADMIN.EPM_TechnicianInformation")
It is giving
DatabaseError: ORA-00900: invalid SQL statement
How can I create query "DESCRIBE ARADMIN.EPM_TechnicianInformation" with cx_Oracle?
I want to get column details of the table.
Please help! Thanks!
The 'desc' command is a SQL*Plus command, not something the database or cx_Oracle understands.
Please check the documentation on cursor description property of cx_Oracle.
You can try the following:
# sql for column details
sql = "SELECT * from ARADMIN.EPM_TechnicianInformation"
cursor.execute(sql)
print(cursor.description)
# This will print out the column description as a list, with each item referring to each column.
reading from How to execute a SQL script with cx_oracle it looks like SQL Plus specific statements are not understood by cx_Oracle
you can try getting the information you need by doing :
SELECT * FROM ALL_TABLES WHERE OWNER= 'ARADMIN' AND TABLE_NAME = 'EPM_TechnicianInformation'
This will give you infos on the table as well

Passing Safe Query Parameters with SQLite in Python

I am working on a project that uses a HTML text input to retrieve data from a SQLite database.
The idea goes like this : the user types string representing a product number and I look into my database for that string.
I have tried to make my query safe for SQL injection as suggested in this tutorial because the data does not come from me.
cursor.execute("SELECT product_number FROM price_history WHERE product_number = %s';", (user_input, ))
However, when I try to execute my code, I get :
sqlite3.OperationalError: near "%": syntax error
There's an extra ' after %s.
Read the first paragraphs of the python docs on sqlite3 that show the correct way to use placeholders.
cursor.execute("SELECT product_number FROM price_history WHERE product_number = (?)", (user_input, )) should work.

PostgreSQL query gives unexpected result

I'm trying to do something extremely simple that works, but not the way I expect it to. I have a database with various tables and for each of those tables, I'm trying to extract the column names from the information schema. I'm using the code below and everything works like a charm (python):
import psycopg2 as pgsql
# code to connect and generate cursor
table = 'some_table_name'
query = 'SELECT column_name FROM information_schema.columns WHERE table_name = %s'
cursor.execute(query, (table,))
result = pd.DataFrame(cursor.fetchall())
print(result)
So far, so good. The problem arises when I replace the query variable with the following:
import psycopg2 as pgsql
# code to connect and generate cursor
table = 'some_table_name'
**query = 'SELECT column_name FROM information_schema.columns WHERE table_name='+table
cursor.execute(query)**
result = pd.DataFrame(cursor.fetchall())
print(result)
If I print the statement, it's correct:
SELECT column_name FROM information_schema.columns WHERE table_name=some_table_name
However, when I run the query, I'm getting this error message:
UndefinedColumn: column "some_table_name" does not exist
LINE 1: ... FROM information_schema.columns WHERE table_name=some_tabl...
some_table_name is a table name as a parameter to the WHERE clause, not a column name. How is this even possible?
Thanks!
Your problem is that you haven't put some_table_name in quotes so it is treated as a column name, not a string literal. Why not stick with the first method which both worked and is in line with the psycopg documentation?

How can I check if a database table exists or not with Python?

I would like to check if a database table exists or not, but I don't know how to do.
I wrote (for example with SQLite, although I use MySQL mainly),
import sqlite3
table_name = "some_table"
connection = sqlite3.connect(db)
cursor = connection.cursor()
table_check = "SELECT name FROM sqlite_master WHERE type='table' AND name={};".format(table_name)
if not cursor.execute(table_check).fetchone(): # if the table doesn't exist
# OR if cursor.execute(table_check).fetchone() == "":
create_table()
else:
update_table()
But, an Error occured and I cannot proceed.
sqlite3.OperationalError: no such column: some_table
I read several Q&A here, but I couldn't get those.
Any advice can help me.
Thank you.
Python 3.5.1
The answer is depending on what rdbms product (mysql, sqlite, ms sql, etc.) you use.
You are getting this particular error in your above query because you do not enclose the value of table_name variable in single quotes.
In mysql you can use information_schema.tables table to query if a table exists.

Can I set user-defined variable in Python MySQLdb?

So My problem is this, I have a query that uses Mysql User-defined variable like:
#x:=0 SELECT #X:=#X+1 from some_table and this code returns a column from 1-1000.
However, this query doesn't work if I sent it through mySQLdb in Python.
connection =MySQLdb.Connect(host='xxx',user='xxx',passwd='xxx',db = 'xxx')
cursor = connection.cursor
cursor.execute("""SET #X:=0;SELECT #X:=#X+1 FROM some_table""")
rows = cursor.fetchall()
print rows
It prints a empty tuple.
How can I solve this?
Thanks
Try to execute one query at a time:
cursor.execute("SET #X:=0;");
cursor.execute("SELECT #X:=#X+1 FROM some_table");
Try it as two queries.
If you want it to be one query, the examples in the comments to the MySQL User Variables documentation look like this:
SELECT #rownum:=#rownum+1 rownum, t.* FROM (SELECT #rownum:=1) r, mytable t;
or
SELECT if(#a, #a:=#a+1, #a:=1) as rownum
See http://dev.mysql.com/doc/refman/5.1/en/user-variables.html

Categories