I'm using pyodbc to access DB2 10.1.0
I have a login account named foobar and a schema with the same name. I have a table named users under the schema.
When I'm logged in as foobar, I can run the following query successfully from the command line:
select * from users
I have a small Python script that I'm using to connect to the database. The script is:
#!/usr/bin/python
import pyodbc
if __name__ == "__main__":
accessString ="DRIVER={DB2};DATABASE=MYDATABASE;SERVER=localhost;UID=foobar; PWD=foobarish1;CURRENTSCHEMA=FOOBAR"
print accessString
cnxn = pyodbc.connect(accessString , autocommit=True)
cursor = cnxn.cursor()
query = "SELECT * FROM USERS"
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
print 'Row data'
print row[0]
cursor.close()
cnxn.close()
When I run the script, I get the following error:
('42S02', '[42S02] [IBM][CLI Driver][DB2/LINUXX8664] SQL0204N "FOOBAR.USERS" is an undefined name. SQLSTATE=42704\n (-204) (SQLExecDirectW)')
This usually means that the schema isn't defined. However, if I change the query in the script to:
VALUES CURRENT SCHEMA
the script runs successfully and it returns
FOOBAR
Does anyone know how to fix this so I can query the user table? Your assistance and insight is appreciated.
EDIT: I've also tried adding the schema directly to the table name, making the query
SELECT * FROM FOOBAR.USERS
and I still get the same error.
I had the same issue and solved it by setting the SCHEMA explicit by query:
SET CURRENT SCHEMA foobar
Related
In Jupyter Notebook, I was able to connect to my work database using pyobdc with 'dsn; userid; pw' connection string successfully. I tested out printing all the table names in the database. Then I tried to run the following code to test a simple query.
================================
query = "select * from TEST_TABLE"
cursor.execute(query)
================================
But I got the following error.
ProgrammingError: ('42S02', '[42S02] [IBM][CLI Driver][DB2/AIX64] SQL0204N "**myusername.TEST_TABLE**" is an **undefined name**. SQLSTATE=42704\r\n (-204) (SQLExecDirectW)')
TEST_TABLE does exist in the database I'm connected to. But for some reason, the code is adding myusername in front of the TEST_TABLE and tells me the table name is not defined.
Try setting up the PyODBC connection as follows:
import pyodbc
dbConn = pyodbc.connect("DSN=<dsn>;UID=<uid>;PWD=<pwd>;DATABASE=<db>")
dbCursor = dbConn.cursor()
query = "SELECT * FROM TEST_TABLE"
dbCursor.execute(query)
where:
dsn = the hostname (or IP address)
uid = the username
pwd = the password
db = the database name
i've been trying to get some data from my db by using below code, but the code is not working. is there any mistake that i made in the code, if so how can i fix it.
NOTE: i took the below code from just a script not a django or flesk web app.
def db():
conn = psycopg2.connect(
"dbname=mydb user=postgres password=****** host=*.*.*.*")
cur = conn.cursor()
cur.execute("""SELECT * FROM MddPublisher""")
query_results = cur.fetchall()
print(query_results)
db()
ERROR: psycopg2.errors.UndefinedTable: relation "mddpublisher" does not exist LINE 1: SELECT * FROM MddPublisher
additionally,i want to show below code to prove that connection is ok. the problem is that i can't receive data from my db whenever i try to execute select command through python.
def print_tables():
conn = psycopg2.connect(
"dbname=mydb user=postgres password=***** host=*.*.*.*.*")
cur = conn.cursor()
cur.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cur.fetchall():
print(table)
print_tables()
OUTPUT:
('MddPublisher',)
This is probably an issue with case sensitivity. Postgresql names are usually normalized to lower case. However, when used inside double quotes, they keep their case. So, to access a table named MddPublisher you must write it like "MddPublisher".
All the gory details are in Section 4.1.1, Identifiers and Key Words in the Postgresql 14 docs.
I am using cx_Oracle module to connect to oracle database. In the script i use two variables schema_name and table_name. The below query works fine
cur1.execute("select owner,table_name from dba_tables where owner ='schema_name'")
But i need to query the num of rows of a table, where i need to qualify the table_name with the schema_name and so the query should be
SELECT count(*) FROM "schema_name"."table_name"
This does not work when using in the code, i have tried to put it in triple quotes, single quotes and other options but it does not format the query as expected and hence errors out with table does not exist.
Any guidance is appreciated.
A prepared statement containing placeholders with variables of the form ...{}.{}".format(sc,tb) might be used
sc='myschema'
tb='mytable'
cur1.execute("SELECT COUNT(*) FROM {}.{}".format(sc,tb))
print(cur1.fetchone()[0])
In this particular case, you could also try setting Connection.current_schema, see the cx_Oracle API doc
For example, if you create table in your own schema:
SQL> show user
USER is "CJ"
SQL> create table ffff (mycol number);
Table created.
SQL> insert into ffff values (1);
1 row created.
SQL> commit;
Commit complete.
Then run Python code that connects as a different user:
import cx_Oracle
import os
import sys, os
if sys.platform.startswith("darwin"):
cx_Oracle.init_oracle_client(lib_dir=os.environ.get("HOME")+"/Downloads/instantclient_19_8")
username = "system"
password = "oracle"
connect_string = "localhost/orclpdb1"
connection = cx_Oracle.connect(username, password, connect_string)
connection.current_schema = 'CJ';
with connection.cursor() as cursor:
sql = """select * from ffff"""
for r in cursor.execute(sql):
print(r)
sql = """select sys_context('USERENV','CURRENT_USER') from dual"""
for r in cursor.execute(sql):
print(r)
the output will be:
(1,)
('SYSTEM',)
The last query shows that it is not the user that is being changed, but just the first query is automatically changed from 'ffff' to 'CJ.ffff'.
I tried retrieving data from a Microsoft SQL database using pypyodbc 1.3.3 with Python 3.5 on Windows but got a pypyodbc.ProgrammingError '[24000] [Microsoft] [SQL Server Native Client 11.0] Invalid cursor state' using the following code:
import pypyodbc
conn = pypyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=uid;PWD=pwd')
cursor = conn.cursor()
sql = '''USE database;
SELECT R0
FROM table;'''
cursor.execute(sql)
results = cursor.fetchone()
print(results)
The SQL works in Microsoft SQL Server Management Studio, the connection and executing worked in another script i wrote to insert into the same database and also works if i remove
results = cursor.fetchone()
So far I tried cursor.fetchone(), cursor.fetchall() and list(cursor) but all produced the same result which leads me to believe that the command itself isn't the problem.
According to this microsoft site it means that there isn't an open cursor, but I can get it's description, so from my understanding there has to be.
It's not a matter of being unable to execute a USE ... statement at all, it's just that we cannot do that as part of a multi-statement batch. So, this will not work ...
crsr.execute("""\
USE master;
SELECT TOP 2 name FROM sys.tables ORDER BY name;
""")
rows = crsr.fetchall() # error
... but this will work fine
crsr.execute("USE master")
crsr.execute("SELECT TOP 2 name FROM sys.tables ORDER BY name")
rows = crsr.fetchall()
(Tested with both pypyodbc 1.3.4 and pyodbc 4.0.21)
I had a similar issue. I was able to resolve this by removing the "USE Database" statement.
You already connected to your db here:
conn = pypyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=server;DATABASE=database;UID=uid;PWD=pwd')
I am trying to drop/delete a table from within Google Cloud SQL using Python (App Engine) but I want the table name to be based on a variable, for simplicity I am using 'hello' here. For some reason it is throwing back an error at me: "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 '-IN' at line 1"
I tried the following:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS %s', (tabNameShort))
conn.commit()
I also tried:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS ' + tabNameShort)
conn.commit()
Any suggestions?
try this:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS `%s`' % tabNameShort)
conn.commit()
A warning: appending the table name directly using '+' can result in an SQL injection vulnerability, if the table name is derived, directly or indirectly, from user input.