I am facing an error while executing a python script.
Checked with directly using the users and password.
Checked with saved the users and pass in variables too.
Script:
import mysql.connector,sys
try:
cnx = mysql.connector.connect (host='localhost', user = 'user', password = 'user#543', port= 3306)
except mysql.connector.errors.ProgrammingError, e:
print time.strftime("%Y-%m-%d %H:%M:%S"),"Error %s" % (e)
sys.exit(1)
except mysql.connector.errors.InterfaceError, e1:
print time.strftime("%Y-%m-%d %H:%M:%S"),"Error %s" % (e1)
sys.exit(1)
cursor = db.cursor()
cursor.execute("select version()")
result_set = cursor.fetchall()
print result_set
Error:
Traceback (most recent call last):
File "test.py", line 3, in <module>
cnx = mysql.connector.connect (host='localhost', user = 'user', password = 'user#543', port= 3306)
AttributeError: 'str' object has no attribute 'connector'
It's a typo. There's a space between connect and the argument list. Change the line to:
cnx = mysql.connector.connect(
host='localhost', user='user', password='user#543', port=3306
)
Related
Im currently attempting to follow a youtube tutorial on how to connect a database through Pycharm however it's not connecting and I'm not sure where the problem is or how I am able to solve it. the code is:
import mysql.connector
from mysql.connector import errorcode
try:
cnn = mysql.connector.connect(
user='root',
password='root',
host='localhost',
database='name')
print("it works")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("something is wrong with username and password")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("database does not exist")
else:
print("E")
cursor = cnn.cursor()
addName = "INSERT INTO name (fName, lName) values (%s, %s)"
fName = "Rae"
lName = "Smith"
empName = (fName, lName)
cursor.execute(addName, empName)
cnn.commit()
cursor.close()
cnn.close()
Once I run it I get the error:
Traceback (most recent call last):
something is wrong with username and password
line 19, in <module>
cursor = cnn.cursor()
NameError: name 'cnn' is not defined
I've seen the user on the tutorial receiving the same warning however when he runs his code there is no error like the one I receive. How I may be able to solve this?
Hey I am having trouble connecting to my PostgreSQL DB through Python. I am following this tutorial However when I attempt to run the code I return the following error:
Traceback (most recent call last):
File "/Users/username/Desktop/Coding/anybody/postgresqltest.py", line 2, in <module>
from config import config
ImportError: cannot import name 'config'
[Finished in 0.201s]
However, I have pip installed config (I am using a virtual environment) and verified using pip list
When I remove from config import config and replace with just import config I receive this error:
module' object is not callable [Finished in 0.127s]
Here is the code I have written, I am a bit stuck on what to do next (the actual database I am connecting to isn't called test btw, this is a different one):
import psycopg2
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
from config import config
def connect():
conn = None
try:
params = config()
print('Connecting to the PostgreSQL DB')
conn = psycopg2.connect(**params)
cur = conn.cursor()
print('PostgreSQL database version:')
cur.execute('Select version()')
db_version = cur.fetchnone()
print(db_version)
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
Put the config function into a separate .py file.
actually you don't need the config module at all in case you have the DB connection parameters:
here's the code that worked for my connection to DB hosted by Elephant (https://api.elephantsql.com/):
import psycopg2
#from config import config
conn = None
conn = psycopg2.connect(
host="your DB host",
database="DB NAME",
user="USER NAME",
password="DB PASSWORD")
try:
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
# create a cursor
cur = conn.cursor()
# execute a statement with cur.execute()
# in this case we get the version
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
main()
also, the docs by psycopg don't mention "config" module:
https://www.psycopg.org/docs/usage.html
I am using a postgres database and connecting it using psycopg2 connector. Here is my code below
import psycopg2
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=port)
cur = conn.cursor()
try:
cur.execute(sql_query)
result = cur.fetchall()
except Exception as e:
print("Could not get results")
conn.rollback()
Now the problem is I receive this error when I try to retrieve data from db
Traceback (most recent call last):
File "/home/ec2-user/connection/dbaccess.py", line 119, in get_results_of_query
result = cur.fetchall()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 20: ordinal not in range(128)
Now on looking up online, I found some posts where they asked to use set_client_encoding('UTF8')
So this is what I did
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=port)
cur = conn.cursor()
conn.set_client_encoding('UTF8')
And then I tried to run it again. But I still receive the same error like before. What am I doing wrong?
I have database in MySQL workbench and I'm running Python code from shell to connect to my database.
But I am unable to import mysql.connector or mysqlDb (got this suggestion from w3school). So I am unable to connect to my database.
I think the question does not concern connecting with Putty, but more about importing mysql.connector in your python script.
"But I am unable to import mysql.connector or mysqlDb ( got this suggestion form w3school)"
--It will be easier to help you if your code is attached to your post.
import mysql.connector
cnx = mysql.connector.connect(########)
think this scrap of code will be helpful."Loading file from Oracle"
def load_file(DT):
ip = ######
port = #####
service_name = '#####'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name)
t = datetime.now().strftime("%Y%m%d%H%M%S")
SQL = "select name...."
fn = "/root/..." + t + ".csv"
fn_tmp = "/root/.." + t + ".csv"
FILE = open(fn_tmp, "w")
FILE.write(
'name...;' + '\n')
out = csv.writer(FILE, delimiter=';')
logging.info("Database connect " + t)
try:
conn = cx_Oracle.connect('####', '###', dsn)
cur = conn.cursor()
cur.execute(SQL)
except cx_Oracle.DatabaseError, exc:
conn = None
error, = exc.args
logging.error(
"Oracle connection problem Error Code:{0}".format(str(error).decode("####",
"ignore").encode("utf-8",
"ignore"))
)
for row in cur:
out.writerow(localize_floats(row))
logging.info("Database disconnect " + t)
try:
cur.close()
conn.close()
except cx_Oracle.DatabaseError, exc:
error, = exc.argsgv[0]
logging.error("Oracle-Error-Code:{0}".format(str(error).decode("####",
"ignore").encode("utf-8",
"ignore"))
)
FILE.close()
os.rename(fn_tmp, fn)
An option that you can try is to use pymysql. More info here. A code snippet is the following:
import pymysql.cursors
connection = pymysql.connect(host='IP',
port=3306,
user='user',
password='pass',
db='database',
charset='utf8mb4',
autocommit=True,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
query = 'Your query'
cursor.execute(query)
connection.close()
I am trying to test that an error is thrown in unittest with Python 3.6 when working with psycopg2. In this case, the database named foo does not existm, and it should throw an OperationalError because the database is not a valid one.
Here is a sample test case:
# -*- coding: utf-8 -*-
import unittest
import psycopg2
import logging
def pull_pg_data(conn, cursor, first, last):
try:
cursor.execute('SELECT first_name, last_name, email, street FROM user_data WHERE first_name =%s AND last_name=%s',(first, last))
except psycopg2.OperationalError as msg:
logging.error(msg)
raise
conn.commit()
result = cursor.fetchall()
return result
class SampleTestCases(unittest.TestCase):
def setUp(self):
try:
self.conn = psycopg2.connect(dbname='postgres', user='postgres', host='localhost', port=5432,
connect_timeout=10)
except psycopg2.OperationalError as msg:
logging.critical(msg)
raise
self.conn.autocommit = True
self.cursor = self.conn.cursor()
self.cursor.execute('DROP TABLE IF EXISTS user_data', [])
self.cursor.execute('CREATE TABLE user_data (first_name TEXT, last_name TEXT, email TEXT, street TEXT)', [])
self.cursor.execute("INSERT INTO user_data(first_name, last_name, email, street) VALUES('someFirstName', 'someLastName', 'some#example.com', '123 road')",[])
def test_pull_pg_data_fail(self):
conn = psycopg2.connect(dbname='foo', user='postgres', host='localhost', port=5432, connect_timeout=10)
cursor = conn.cursor()
self.assertRaises(psycopg2.OperationalError, pull_pg_data, conn, cursor, 'someFirstName', 'someLastName')
if __name__ == '__main__':
unittest.main()
When I run the test, it does indeed throw an error, but it fails the test. I don't know what I am doing incorrectly with assertRaises, because I do want to test that the error is thrown when I try to connect to a database that does not exist.