general connection to a mysql server - python

Is there a way to make a general connection to a mysql server and not specifically to any one of its databases? I found the following code snippet. The connect method connects to a specific database called employees.
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees')
cnx.close()

Yes, You can make the same connection without specifying the database name:
cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1')
It would be the same as connecting from the terminal using:
mysql -h 127.0.0.1 -u scott -ptiger
Note: 127.0.0.1 is your localhost.
Also, I usually do not store the actual connection information in the script. I would do something more like this (If you can):
def CloseConnection(cnxIn, cursorIn):
cursorIn.close()
cnxIn.close
return
user = input('Enter your user name: ')
user = user.strip()
password = getpass.getpass()
host = input('Enter the host name: ')
host = host.strip()
cnx = mysql.connector.connect(user=user, password=password, host=host)
cursor = cnx.cursor(buffered=True)
cursor.execute ('select VERSION()')
row = cursor.fetchone()
CloseConnection(cnx, cursor)

Related

A database is not being created in python PostgreSQL

import psycopg2
from config import host, user, password, db_name, port
connection = None
try:
# подключаемся к базе
connection = psycopg2.connect(
host=host,
user=user,
password=password,
database=db_name,
port=port
)
connection.autocommit = True
# cursor нужен чтобы взаимодействовать с БД
# сейчас создаем нашу БД
with connection.cursor() as cursor:
cursor.execute(
"""CREATE TABLE IF NOT EXISTS data1 (
price int NOT NULL,
styles text NOT NULL,
runes text);"""
)
except Exception as _ex:
print("[INFO] Error while working with PostgreSQL", _ex)
finally:
if connection:
connection.close()
print("[INFO] PostgreSQL connection closed")
config
host = "127.0.0.1"
user = "postgres"
password = "14101999"
db_name = "data"
port = "5432"
When executing , it outputs [INFO] Error while working with PostgreSQL
I do not understand at all what the problem is and why the database is not being created, I seem to have indicated everything correctly in config...
I don't see where you are creating a database. psycopg2.connect() has to connect to an existing database. So either you create the database outside the Python script or you connect to an existing database, best practices the database named postgres, and then issue a CREATE DATABASE <some_name>. You would then need to close the existing connection and create a new one to the new database.

sqlalchemy, postgres, docker

I am struggling to understand why my query below returns the following error, when I past it directly from postgres where it works fine. I have read putting the table name in quotes but this does not work :/.
from sqlalchemy import create_engine
db_name = 'blahh'
db_user = 'blahhd'
db_pass = 'blhd'
db_host = 'localhost'
db_port = 5432
## Connect to to the database
db_string = 'postgres://{}:{}#{}:{}/{}'.format(db_user, db_pass, db_host, db_port, db_name)
db = create_engine(db_string)
connection = db.connect()
connection.execute('select cake.name, cake.industry, cake.created_at from cake limit 10;')
connection.close()
error:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "cake" does not exist
LINE 1: ... cake limi...
^
As explained in the SQLAlchemy documentation, you are missing out the connection object. create_engine simply represents a connection resource. You need to connect to it and later close the connection. You may also need to add the method .fetchall() to actually view the list of items from your connection.
If you try something like this:
from sqlalchemy import create_engine
db_name = 'blahh'
db_user = 'blahhd'
db_pass = 'blhd'
db_host = 'localhost'
db_port = 5432
## Connect to to the database
db_string = 'postgres://{}:{}#{}:{}/{}'.format(db_user, db_pass, db_host, db_port, db_name)
db = create_engine(db_string)
connection = db.connect()
connection.execute('select cake.name, cake.industry, cake.created_at from cake limit 10;').fetchall()
connection.close()

User's input to be used as connection credentials to sql server with python

I am able to establish a connection to the database when using this code :
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0}; Server=1070010-01; uid=sa; pwd=SDKJ-1111; Database = TEST_DB; Trusted_Connection=No;')
I've manually put in the user name and password . Now ,how would I write my code in order to make it take the user input and use it as credentials ? How do I set a variable for example and call it inside the function later on ?
Thank you
Try this one
userName = input("Enter DB Username: ")
pswd = input("Enter DB Password: ")
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0}; Server=1070010-01; uid='+ userName +'; pwd='+pswd+'; Database = TEST_DB; Trusted_Connection=No;')

How do I overcome this sql connectivity error with python?

I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.

Python: How to connect to a MySQL db

I am trying to write a script that connects to a server, then connects to a MySQL db (which I currently can do via Navicat - so I know my username and password for the MySQL connection are correct).
Here is what I’ve written so far:
import socket
from ssh2.session import Session
import mysql.connector
host = 'servername.logserverlog.net'
user = 'username'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 22))
session = Session()
session.handshake(sock)
session.userauth_publickey_fromfile(user, r'C:\Users\user\Docs\ssh-key')
cnx = mysql.connector.connect(user='username', password='$gHj1aFaVFRfhl*C', database='analyst_db')
The error I am getting reads:
File “C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\mysql\connector\connection.py”, line 176, in _auth_switch_request raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user ‘username’#‘localhost’ (using password: YES)
Given that I have already confirmed my user and password are valid, I have also tried editing the password string to a raw string (to see if somehow the Python string wasn’t being received by the MySQL db correctly) and received the same error.
So, I’m not sure why the error keeps coming up.
I ended up learning that just because I created an SSH connection, I still needed to set up an SSH Tunnel with port forwarding, so the script knows where to communicate. I made the assumption that the connection itself would tell the script where to look (when in reality the port forwarding tells it where to look and listen).
So I was skipping a step. The final working script uses SSHTunnelForwarder from the sshtunnel library.
import mysql.connector
from datetime import date, datetime, timedelta
from sshtunnel import SSHTunnelForwarder
ssh_host = 'servername.net'
ssh_port = 22
ssh_user = 'serveruser'
ssh_key = "C:\\Users\\user\\ssh\\public key"
ssh_remote_port = 3306
with SSHTunnelForwarder(
(ssh_host, ssh_port),
ssh_username=ssh_user,
ssh_private_key=ssh_key,
remote_bind_address=('127.0.0.1', ssh_remote_port)
) as server:
cnx = mysql.connector.connect(user='username', password='password', database='analyst_db, host='localhost', port=server.local_bind_port)
cur = cnx.cursor()

Categories