How to connect with SQLALCHEMY to a database?

0

I am doing a test in Python to verify that the database of a machine is active.

My problem is that when I connect it gives me the error:

  

"sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1045," Access denied for user 'david' @ 'localhost' (using password: NO) ")"

and my code is:

    connection = 'sqlite:///'+user+':'+password+'@'+str(host)+':'+str(port)+"/"+dbname
    self.engine = sqlalchemy.create_engine(connection) #Establish connection
    self.connection = self.engine.connect()
    print('Connected to '+connection)
    result = self.connection.execute('SELECT COUNT(name) FROM table WHERE name LIKE "%pdf"')

In 'user' I do not have a defined "david", as it appears in the error and as you can see if I use a password.

    
asked by Navarrinsky 17.11.2016 в 11:59
source

2 answers

0

According to the tags you have used I see that you want to connect to a mysql database, but in your code you use the sqlite driver (this only has a user and address). You have to use the mysql driver:

Here is an example:

from sqlalchemy import *

engine = create_engine('mysql://'+user+':'+password+'@+str(host)+'/'++dbname+'?charset=utf8&use_unicode=0', pool_recycle=port)

connection = engine.connect()
    
answered by 17.11.2016 / 13:47
source
0

You did not specify if you are using a MySQL or SQLlite DBMS.

If you want to connect to a MySQl database, I recommend using pymysql , right now I am using it for a project and after trying several libraries this is the one that worked best for me.

It is installed using pip install pymysql . Here I leave an example code of its use and you will see that it is quite simple and it will help you to verify that the bd is active:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='', db='tweetsjun2016', charset = 'utf8mb4')

cur = conn.cursor()

cur.execute(""" 
            SELECT * FROM 20160607_tweets
            WHERE 20160607_tweets.creation_date >= '2016-06-07 10:51'
            LIMIT 5
            """)

for row in cur:
    print(row) # Lista records o tuplas

Basically if you execute the statement pymysql.connect without throwing an error, it means that you connected correctly. I would do something like that for the test:

import pymysql
try:
 conn = pymysql.connect(host=str(host), port=port, user='user', passwd=password, db=dbname, charset = 'utf8mb4')
except pymysql.err.OperationalError:
 print("Error conectando con la base de datos.")
    
answered by 18.11.2016 в 16:40