I cant grab columns from a table in a database in python - python

I am trying to grab information from columns in a database using python.
code:
import pyodbc
conn = pyodbc.connect(r'DSN=MACCD')
cursor = conn.cursor()
cursor.execute('SELECT first,second,third,fourth,fifth * FROM Test')
for column in cursor.fetchall():
print(column)
error:
Traceback (most recent call last):
File "C:\Users\jgp22\Desktop\Python\GrabDatas.py", line 5, in <module>
cursor.execute('SELECT first,second,third,fourth,fifth * FROM Test')
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft
Access Driver] Syntax error (missing operator) in query expression 'fifth
*'. (-3100) (SQLExecDirectW)")

You have a bad SQL query. Cannot put * like that in select queries
Either put a comma before asterisk
SELECT first,second,third,fourth,fifth,* FROM Test;
Or remove asterisk
asterisk is used to represent all columns in sql so using it in your query means you are fetching all columns, therefore it is useless in this scenario to use asterisk is u want only few columns

Related

INSERT INTO MS Access with python ans pyodbc.. Error after inserting some rows

I am trying to insert data into ms access
I successfully insert some rows and suddenly I get an error. After the error, I can't INSERT more rows.
An example:
import pyodbc
cnxn = pyodbc.connect(your_driver_and_path_to_ms_access)
crsr = cnxn.cursor()
query1 = '''CREATE TABLE tbl01 (Id INT, name VARCHAR(25)) '''
crsr.execute(query1)
cnxn.commit()
query2 = ''' INSERT INTO tbl01 (Id,name) VALUES(?,?) '''
for i in range(5000):
param = [i] + ['test']
crsr.execute(query2, param)
cnxn.commit()
crsr.close()
Error: ('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] Cannot open database '|'. It may not be a database that your application recognizes, or the file may be corrupt. (-1206) (SQLExecDirectW)")
Inserting up 2000 most of the time works fine.
And also reading the table after the Error works.
query3 = ''' select * from tbl01 '''
crsr.execute(query3)
crsr.fetchone()
Thanks in advance

Dremio ODBC with Python

Getting below error while running this code in Python, If anyone could advise me on this that would be appreciated. Thanks
dataframe = pandas.read_sql(sql,cnxn)
DatabaseError: Execution failed on sql 'SELECT * FROM train_data': ('HY000', "[HY000] [Dremio][Connector] (1040) Dremio failed to execute the query: SELECT * FROM train_data\n[30038]Query execution error. Details:[ \nVALIDATION ERROR: Table 'train_data' not found\n\nSQL Query SELECT * FROM train_data\nstartLine 1\nstartColumn 15\nendLine 1\nendColumn 24\n\n[Error Id: 24c7de0e-6e23-44c6-8cb6-b0a110bbd2fd on user:31010]\n\n (org.apache.calcite.runtime.CalciteContextException) From line 1, column 15 to line 1, column 24: ...[see log] (1040) (SQLExecDirectW)")
You only need to provide your Space name, just before your table name.
for example:
SELECT * FROM
SpaceName.train_data
This is a query to fetch data from Dremio Space, Dremio source cannot be used for data ingestion. Dremio Source only be used to establish a connection between database and Dremio.
this is being solved, it says that table does not exist, should give a valid table, in dremio it can be inside a specific space

Error during saving query data into dataframe

I am trying to access sqlite db - test.db and running simple query "SELECT * FROM TABLE" and trying to save it in dataframe. It seems the code is fine as I searched and found similar codes that seem to work for others.
NOTE: I am running the code in Jupyter iNotebook.
import sqlite3
import pandas as pd
con = sqlite3.connect('test.db')
myFrames = pd.read_sql_query("SELECT * FROM TABLE", con)
I get error
Error OperationalError: near "TABLE": syntax error
(lots of lines in between)
DatabaseError: Execution failed on sql 'SELECT * FROM TABLE': near "TABLE": syntax error
Also, This piece prints out rows very well. So connection is working
conn = sqlite3.connect("test.db")
cur = conn.cursor()
for row in cur.execute("SELECT * FROM test_rank"):
print(row)
Table is a reserved keyword. Replace it with the real name of the table.

"cannot find the input table or query" error for a SELECT statement

I am saving MS Access tables as CSV files using Python. There is a table in the MS Access database that is named 'Perm_Site Info'. There is a space in the naming in MS Access. When I run the below snippet, the code blows up. I have tried having single and as well as double quotes in the cursor.execute but no fruition. I request your kind assistance in order to understand how to fix this.
import pyodbc
import csv
conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Access\\permissions.accdb")
conn = pyodbc.connect(conn_string)
cursor = conn.cursor()
cursor.execute("select * from Perm_Site Info;")
with open('C:\\Desktop\\Python Files\\Perms_Site_Info.csv','wb') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([i[0] for i in cursor.description])
writer.writerows(cursor)
cursor.close()
conn.close()
print 'All done for now'
The error:
cursor.execute("select * from Perm_Site Info;")
ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Microsoft Access Driver] The Microsoft Access database engine cannot find the input table or query 'Perm_Site'. Make sure it exists and that its name is spelled correctly. (-1305) (SQLExecDirectW)")
Try using brackets around the entire table name. It's barking because it doesn't know what to do with the space.
cursor.execute("select * from [Perm_Site Info];")

PostgreSQL: Unable to drop a specific table named "user"

I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute("DROP TABLE user;")
conn.commit()
conn.close()
It spits out the following error
Traceback (most recent call last):
File "dev_psycog.py", line 20, in <module>
cur.execute("DROP TABLE user;")
psycopg2.ProgrammingError: syntax error at or near "user"
LINE 1: DROP TABLE user;
I can delete any other table in my database just fine, but I can't seem to delete my table called "user". Is it because "user" is a reserved keyword?
Quote "user" as below
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute('DROP TABLE "user";')
conn.commit()
conn.close()
See here.
There is a second kind of identifier: the delimited identifier or
quoted identifier. It is formed by enclosing an arbitrary sequence of
characters in double-quotes (").

Categories

Resources