Error when connecting to sql using Python - python

I am using Python library pymssql to connect to a database. I have never used it before so the error might look trivial.
from os import getenv
import pymssql
server = getenv("192.xxx.xxx.xx")
user = getenv("john.constantine")
password = getenv("xxxxxxx")
conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
cursor.execute('SELECT * from table')
rows = cursor.fetchall()
for row in rows:
print row
conn.close()
I get the following error:
Traceback (most recent call last):
File "C:\Users\Documents\Demo_DB.py", line 8, in <module>
conn = pymssql.connect(server, user, password, "tempdb")
File "pymssql.pyx", line 635, in pymssql.connect (pymssql.c:10734)
File "_mssql.pyx", line 1902, in _mssql.connect (_mssql.c:21821)
File "_mssql.pyx", line 552, in _mssql.MSSQLConnection.__init__ (_mssql.c:5891)
TypeError: argument of type 'NoneType' is not iterable
[Finished in 0.2s with exit code 1]
I connect to DB using these credentials.

Related

PYMYSQL ERROR pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax ")

Here is the full error
Traceback (most recent call last):
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/test.py", line 26, in <module>
handler()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/test.py", line 17, in handler
cursor.execute('SELECT * FROM Reads')
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/cursors.py", line 148, in execute
result = self._query(query)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/cursors.py", line 310, in _query
conn.query(q)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 775, in _read_query_result
result.read()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 725, in _read_packet
packet.raise_for_error()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.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 'Reads' at line 1")
For context here is my code
from multiprocessing import connection
import pymysql
from pymysql.cursors import Cursor
# RDS config
endpoint = '********'
username = '********'
password = '********'
database_name = '*********'
#connection config
connection = pymysql.connect(host=endpoint,user=username,passwd=password,db=database_name)
def handler():
cursor = connection.cursor()
cursor.execute('SELECT * FROM Reads')
rows = cursor.fetchall()
for row in rows:
print("{0} {1} {2} {3}".format(row[0], row[1], row[2], row[3]))
handler()
I have 2 other tables in my database which work fine when i query them however this table seems to be the only one causing an error.
Feel free to ask for more if this is too vague
It's worth checking manual in cases like this - and Reads is a reserved word therefore must be backticked - better still don't use reserved words or you will forever have to remember to backtick in code..

Read table from MySQL - Python

I have MySQL ( Database: items, Table: issuelist )
I want to read and print out by python... but when I run code as below, it show error.
import mysql.connector
#from mysql.connector import Error
mydb = mysql.connector.connect(
host="localhost",
#user="yourusername",
#passwd="yourpassword",
database="items"
)
mycursor = mydb.cursor()
sql_statement = "SELECT * FROM issuelist"
mycursor.execute(sql_statement)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Traceback (most recent call last): File
"C:\Users\Administrator\Desktop\Chatbot - ReadData\ExcelMySQL.py",
line 8, in
database="items" File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector__init__.py",
line 219, in connect
return MySQLConnection(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 104, in init
self.connect(**kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\abstracts.py",
line 960, in connect
self._open_connection() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 292, in _open_connection
self._ssl, self._conn_attrs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 212, in _do_auth
self._auth_switch_request(username, password) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 256, in _auth_switch_request
raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied
for user ''#'localhost' (using password: NO)
How to do resolve ?
Thanks you so much!
The error message is quite explanatory :
Access denied for user ''#'localhost' (using password: NO)
You can't just connect to mysql with no account...
The error msg clearly shows the mistake -- The connect info is not correct. That is ,in your code, make sure the info of the host,user,passwd and database are all correct?

MySQLdb query command, not fetching correct database (python)

fixed: just using mysql.connector package now.
i am a few programming with python now and i wanted to create a use login/logout system with a database linked to a self created web platform for managment, logging, etc...
now i wanted to perform a query to get all users from my database but for some reason im not able to get any results i tried:
# as requested, connector method.
def initiate_connection(self):
return MySQLdb.connect("localhost", "root", "", "tester")
# This works !
def get_database_version(self):
db = self.initiate_connection() # Instantiate db connection
curs = db.cursor() # Server sided cursors - ref more info: https://mysqlclient.readthedocs.io/user_guide.html#cursor-objects
curs.execute("SELECT VERSION();")# Query command
data = curs.fetchone() # Fetch result.
db.close() # Close conn
return data
# This doesnt? :(
def get_users(self):
db = self.initiate_connection() # Instantiate db connection
curs = db.cursor() # Server sided cursors - ref more info: https://mysqlclient.readthedocs.io/user_guide.html#cursor-objects
curs.execute("SELECT name FROM users")# Query command
data = curs.fetchone() # Fetch result.
db.close() # Close conn
return data
But i get an uknown column error, so i tried selecting everything to see what i get from that result: Nonetype, Also ! i am able to retrieve version from database so i assume im connected properly.
Im pretty clueless in what im doing wrong here any ideas?
Also db structure is:
db->tester
table->users
- id
- name
- password
- salt
- email
Edit:
Actual error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\Programmas\PyCharm Community Edition 2019.2.5\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "D:\Programmas\PyCharm Community Edition 2019.2.5\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/oj/PycharmProjects/RegisteryHandeler/DatabaseHandler.py", line 25, in <module>
print(database_handler().get_users())
File "C:/Users/oj/PycharmProjects/RegisteryHandeler/DatabaseHandler.py", line 18, in get_users
curs.execute("SELECT name FROM users")# Query command
File "C:\Users\oj\PycharmProjects\RegisteryHandeler\venv\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
res = self._query(query)
File "C:\Users\oj\PycharmProjects\RegisteryHandeler\venv\lib\site-packages\MySQLdb\cursors.py", line 315, in _query
db.query(q)
File "C:\Users\oj\PycharmProjects\RegisteryHandeler\venv\lib\site-packages\MySQLdb\connections.py", line 239, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'name' in 'field list'")

I need a hint for sqlite3

I am trying to retrieve values from db and I am stack from start because sqlite3 is unable to open the db file after I was giving the right path.
Version 1:
sqlite_file = os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite')
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
Version 2:
sqlite_file = app.config['SQLALCHEMY_DATABASE_URI']
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
Where:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite')
In both situations the error is
Error on request:
Traceback (most recent call last):
File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/werkzeug/serving.py", line 209, in run_wsgi
execute(self.server.app)
File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/werkzeug/serving.py", line 197, in execute
application_iter = app(environ, start_response)
File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/ubuntu/workspace/avb/app.py", line 222, in <module>
conn = sqlite3.connect(sqlite_file)
sqlite3.OperationalError: unable to open database file
For sqlite3.connect() start out using the actual filename (e.g. example.db) as the argument.
Same for environ.get(): use the actual filename, not the sqlite:/// address.

Connecting to Kerberized hadoop cluster using python module impyla

I am using impyla module to connect to kerberized hadoop cluster. I want to access
hiveserver2/hive but I was getting the below error:
test_conn.py
from impala.dbapi import connect
import os
connection_string = 'hdp296m1.XXX.XXX.com'
conn = connect(host=connection_string, port=21050,auth_mechanism="GSSAPI",kerberos_service_name='testuser#Myrealm.COM',password='testuser')
cursor = conn.cursor()
cursor.execute('select count(*) form t_all_types_simple_t')
print cursor.description
results = cursor.fetchall()
Stacktrace:
[vagrant#localhost vagrant]$ python test_conn.py
Traceback (most recent call last):
File "test_conn.py", line 4, in <module>
conn = connect(host=connection_string, port=21050, auth_mechanism="GSSAPI",kerberos_service_name='testuser#Myrealm.COM',password='testuser')
File "/usr/lib/python2.7/site-packages/impala/dbapi.py", line 147, in connect
auth_mechanism=auth_mechanism)
File "/usr/lib/python2.7/site-packages/impala/hiveserver2.py", line 758, in connect
transport.open()
File "/usr/lib/python2.7/site-packages/thrift_sasl/__init__.py", line 61, in open
self._trans.open()
File "/usr/lib64/python2.7/site-packages/thrift/transport/TSocket.py", line 101, in open
message=message)
thrift.transport.TTransport.TTransportException: Could not connect to hdp296m1.XXX.XXX.com:21050
testuser is my kerberos principal which I will be using to do kinit.
Your connection appears to be incorrect.. Try,
from impala.dbapi import *
import sys, os
# set your parms
host=os.environ.get("CDH_HIVE",'x.x.x.x')
port=os.environ.get("CDH_HIVE_port",'10000')
auth_mechanism=os.environ.get("CDH_auth",'GSSAPI')
user='hive'
db='mydb'
# No password use kinit
password=''
# hive is principal with krb
kbservice='hive'
class Hive:
def __init__(self,db):
self.database=db
self.__conn = connect(host=host,
port=port,
auth_mechanism=auth_mechanism,
user=user,
password=password,
database=db,
kerberos_service_name=kbservice
)
self.__cursor = self.__conn.cursor()
h = Hive(db)

Categories