Running Py ODBC queries? - python

Trying to query for dates in an Access DB, and it keeps returning the follow error:
Traceback (most recent call last):
File "C:/Users/sniederriter/Desktop/SATG.py", line 10, in <module>
for row in cursor.execute(SQL):
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1605, in execute
self.execdirect(query_string)
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1631, in execdirect
check_success(self, ret)
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 986, in check_success
ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 954, in ctrl_err
raise ProgrammingError(state,err_text)
pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'Date *'.")
Here is my code:
import pypyodbc
DBfile = (r'C:\Users\sniederriter\Desktop\SATGexpenses.accdb')
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBfile)
cursor = conn.cursor()
print(DBfile)
SQL = 'SELECT Date * FROM 20142015;'
for row in cursor.execute(SQL):
print (row.Date)
cursor.close()
conn.close()

Your MySQL query is wrong. Following code selects all fields from the table:
SELECT * FROM Table
If you want specific fields write:
SELECT field1, field2, field3 FROM table
But only do one of the things. Either all or specified fields.

Related

How to export MYSQLdb table to CSV on Debian?

I want to export MYSQLdb tables into .csv format.
I tried this:
connection = MySQLdb.connect(host='localhost',
user='***',
passwd='***',
db='database1',
use_unicode=True,
charset="utf8")
cursor = connection.cursor()
query = """ select *
from example_table1
into outfile 'MYFOLDER'
fields terminated by ';'
enclosed by '"'
lines terminated by '';
"""
cursor.execute(query)
connection.commit()
cursor.close()
I get this error message:
Traceback (most recent call last):
File "mysql_export_to_csv.py", line 46, in <module>
cursor.execute(query)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorvalue
_mysql_exceptions.InternalError: (1, 'Can\'t create/write to file \'/usr/src/Python-2.7.13/output.csv\' (Errcode: 30 "Read-only file system")')
What is the problem in this code? Why I can't export it to .csv?
I suggest to try saving your in a directory where you surely have write permissions like /tmp/
Like this:
connection = MySQLdb.connect(host='localhost',
user='***',
passwd='***',
db='database1',
use_unicode=True,
charset="utf8")
cursor = connection.cursor()
query = """ select *
from example_table1
into outfile '/tmp/myfile.csv'
fields terminated by ';'
enclosed by '"'
lines terminated by '';

Python with mysql query insertion - single parameter

Below are the code that is not working
#!/usr/bin/python
import urllib
import datetime
import mysql.connector
data['price'] = 100
# Write to database
cnx = mysql.connector.connect(user='user', password='pw', database='db')
cursor = cnx.cursor()
query = ("INSERT INTO records(price) VALUES(%s) ")
cursor.execute(query, (data['price']))
cnx.commit()
cursor.close()
cnx.close()
MySQL has the corresponding table and column.
id (PRIMARY INT AUTO_INCREMENT)
price (FLOAT)
There is no connection problem.
It gives the following error. Any idea?
Traceback (most recent call last): File "./sys-fetchdata.py", line
22, in
cursor.execute(query, (data['price'])) File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line
507, in execute
self._handle_result(self._connection.cmd_query(stmt)) File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line
722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File
"/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line
640, in _handle_result
raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s)' at line 1
the MySQLCursor.execute() method takes a tuple (or a dict) as second (params) argument.
in your case: it should be (data['price'], ) (note the additional comma; without it the brackets have no effect) instead of (data['price']).
Let's try to find a solution:
Do not execute your query, instead mogrify and print it. For example:
query = ("INSERT INTO records(price) VALUES(%s) ")
query_to_be_executed = cursor.mogrify(query, (data['price']))
print(query_to_be_executed)
Next try to execute your printed query manually in bash or phpMyAdmin and fix it.
Finally use fixed query in your python code.

Insert ERROR - mysql connector python 2.7

I am attempting to insert some sentiment analysis results (google cloud language API) into a mysql database. I am using the mysql connector.
import mysql.connector
from google.cloud import language
cnx = mysql.connector.connect(user='blahuser', password='Blahpw',
host='BlahIP',
database='FeedbackDB')
cursor = cnx.cursor(buffered=True)
CoreSQL = ("SELECT ResID, TextResp FROM Response")
cursor.execute(CoreSQL)
client = language.Client()
for row in cursor:
document = client.document_from_text(row[1])
sent_analysis = document.analyze_sentiment()
sentiment = sent_analysis.sentiment
annotations = document.annotate_text(include_sentiment=True, include_syntax=True, include_entities=True)
print(row[0], sentiment.score, sentiment.magnitude)
ResID_ =row[0]
PhraseSent_ = sentiment.score
PhraseMag_ = sentiment.magnitude
SQLInsertCmd = ("INSERT INTO PhraseAnalysis (ResID, PhraseSent, PhraseMag), VALUES (%s,%s,%s)");
cursor.execute(SQLInsertCmd, (ResID_, PhraseSent_,PhraseMag_))
cnx.commit()
cursor.close()
cnx.close()
The error I get indicates I have an issue with my INSERT statement :
python tm16.py
(1, -0.4, 2.2)
Traceback (most recent call last):
File "tm16.py", line 27, in <module>
cursor.execute(SQLInsertCmd, (ResID_, PhraseSent_,PhraseMag_))
File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 559, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 494, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 396, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ' VALUES (1,-0.4,2.2)' at line 1
There are lots of INSERT examples online, but I haven't be able to resolve. New to coding- no doubt something simple. Can someone point out where I am going wrong?
Mike
You have an unnecessary comma after the end of the fields list.

Pypyodbc.DataError trouble with database

I am trying to figure out why doesn't my test programme in python work.
I can access the database just fine from MySql Workbench, and I think I did everything right with the programming part, I also went to Administrative Tools and added my database to ODBC Database Sources, here is my test programme, if anyone can figure out what's wrong:
import pypyodbc
conn = pypyodbc.connect("DSN=database")
def func():
l = []
cur = conn.cursor()
try:
cur.execute("SELECT foo FROM table")
except pypyodbc.DatabaseError:
pass
conn.commit()
for i in cur:
l.append(i)
conn.close()
cur.close()
func()
The Error I'm getting is:
Traceback (most recent call last):
File "D:/path/test.py", line 21, in <module>
func()
File "D:/path/test.py", line 14, in func
for i in cur.fetchall():
File "D:/path/test.py", line 1819, in fetchall
row = self.fetchone()
File "D:/path/test.py", line 1893, in fetchone
check_success(self, ret)
File "D:/path/test.py", line 986, in check_success
ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
File "D:/path/test.py", line 956, in ctrl_err
raise DataError(state,err_text)
pypyodbc.DataError: ('22018', '[22018] [MySQL][ODBC 5.3(a) Driver][mysqld-5.5.5-10.0.17-MariaDB]')
Error 22018 is an "invalid character" error. One common cause is trying to use the ANSI ("(a)") version of MySQL Connector/ODBC to retrieve Unicode data. In that case the solution is to use the Unicode ("(w)") version of the driver instead.

Syntax Error when inserting data with variables in MySQLdb Python

I am trying to insert some data into a MySQL DB with Python and MySQLdb. When i do the following:
query = "INSERT INTO universitats (universitat) VALUES ('%s')" % (lloc)
cursor.execute(query)
db.commit()
I get this error:
Traceback (most recent call last):
File "read.py", line 39, in <module>
cursor.execute(query)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "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 'Hospitalet de Llobregat')' at line 1")
What am I doing wrong?
This lines:
query = "INSERT INTO universitats (universitat) VALUES ('%s')" % (lloc)
cursor.execute(query)
should look like this
query = "INSERT INTO universitats (universitat) VALUES (%s)"
cursor.execute(query,(lloc,))
and then commit.

Categories