MySQL connection with Python is not working - python

I want to connect with MySQL through Python, although I am successful in connecting using directly writing the credentials like user name, passwd, etc, but I want to make it a little dynamic. So I tried:
import mysql.connector
import pandas as pd
def connection():
host=input('Enter host')
user=input('Enter User Name')
passwd=int(input('passwd'))
database=input('database')
mydb= mysql.connector.connect(host="host", user="user", passwd="passwd", database="database")
return mydb
connection()
However, it gives error in the end:
InterfaceError: 2003: Can't connect to MySQL server on 'host:3306' (11001 getaddrinfo failed)
Please help me out. And if you have better solution while bringing some dynamic user input credential, I will be really grateful. Thank you.

You are passing stirng like "host" to the database and not the variables
So remove the double quotes like
import mysql.connector
import pandas as pd
def connection():
host=input('Enter host')
user=input('Enter User Name')
passwd=int(input('passwd'))
database=input('database')
mydb= mysql.connector.connect(host=host, user=user, passwd=passwd, database=database)
return mydb
connection()

In the connect method of the mysql.connector you are hardcoding the values when you pass them as strings.
Use mysql.connector.connect(host=host, user=user, passwd=passwd, database=database) instead.
You're also parsing the password to a int, I don't think mysql will like that, just use it as a string.

Related

Having trouble connecting with MySQL.connector in python

I am learning how to do MySQL in python using the mysql.connector module. However, whenever I try creating a connection, I get the error "mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (10061 No connection could be made because the target machine actively refused it)".
I done the exact same as the example that I am using states, and it still isn't working.
Below is the two different type of the example provided:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
and
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword"
)
print(mydb)
I tried exactly what the example said, and it didn't work. I also tried using a different username and password, but kept on getting the same error.
Any idea what I can do to get the expected output which, according to the second example that I am referring to, is:
<mysql.connector.connection.MySQLConnection object ar 0x016645F0>
?
Thank you in advance
import mySQL.connector
Mybd=mysql.connector.connect(
host='myusername',
user='myusername',
password='mypassword',
database='mydatabase')
Cursor=mycon.cursor()
Cursor.execute('show databases')
Data=cursor.fetchall()
for row in data:
Print(row)
mycon.close()

How to share a mysql connection that is inside a function?

I am a beginner in python and mysql. I have a small application written in Python that connects to remote mysql server. There is no issues to connect and fetch data. It works fine then the code is outside a function. As I want to close and open connections, execute different queries from several functions inside my application, I would like to be able to call a function to establish a connection or run a query as needed. It seems that when I create an connection, that connection can not be used outside the function. I would like to implement something like this:
mydbConnection():
....
mydbQuery():
....
connected = mydbConnection()
myslq = 'SELECT *.......'
result = mydbQuery(mysql)
And so on...
Thanks for any direction on this.
import mysql.connector
from mysql.connector import Error
def mydbConnection(host_name, user_name, user_password):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
connection = mydbConnection("localhost", "root", "")
In the above script, you define a function mydbConnection() that accepts three parameters:
host_name
user_name
user_password
The mysql.connector Python SQL module contains a method .connect() that you use in line 7 to connect to a MySQL database server. Once the connection is established, the connection object is returned to the calling function. Finally, in line 18 you call mydbConnection() with the host name, username, and password.
Now, to use this connect variable, here is a function:
def mydbQuery(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
To execute queries, you use the cursor object. The query to be executed is passed to cursor.execute() in string format.
Create a database named db for your social media app in the MySQL database server:
create_database_query = "CREATE DATABASE db"
mydbQuery(connection, create_database_query)

How to fix this error "Connection Error with MySQL database" in python

I an setting up the connection with the MySQL server.
This is the code I wrote and got the errors:
import mysql.connector as mysql
def user_registration():
connection_to_mysql = mysql.connect(host='localhost', user='root',
passwd='aWais$777')
Please first trying with double quotes i.e. " " with password parameter passing. If not success then trying double quotes with all passing parameter i.e. host, user and password.
Because of passwd field contains this symbol '$' that's why not accepting.
For more info visit check this code: https://www.w3schools.com/python/python_mysql_getstarted.asp
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
Try using password instead of passwd and make sure to specify database.

Write Pandas Dataframe to MYSQL database with SSH

The Problem
I would like to use the pandas to_sql to write a dataframe to a MYSQL table. However, my connection requires SSH.
What I have tried
I have a successful connection to execute queries with pymysql, but being able to directly use a function like to_sql would make my life a lot easier to be able to directly push the data like that. See below for my code that I'm working with.
from sshtunnel import SSHTunnelForwarder
import pymysql as db
import pandas as pd
import numpy as np
host = 'host'
localhost = 'localhost'
ssh_username = 'ssh_username'
private_key = '/path/'
# database variables
user='user'
password='password'
database='database'
#query function that works for pulling from database
def query(q):
with SSHTunnelForwarder(
(host, 22),
ssh_username=ssh_username,
ssh_private_key=private_key,
ssh_private_key_password="password",
remote_bind_address=(localhost, port)
) as server:
conn = db.connect(host=localhost,
port=server.local_bind_port,
user=user,
passwd=password,
db=database)
return pd.read_sql_query(q, conn)
# What you need to for to_sql
conn = db.connect(host=host,
port=port,
user=user,
password=password,
db=database)
# test df
np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
'feature1': np.random.random(number_of_samples),
'feature2': np.random.random(number_of_samples),
'class': np.random.binomial(2, 0.1, size=number_of_samples),
},columns=['feature1','feature2','class'])
# to_sql
frame.to_sql(con=conn, name='test_table', if_exists='replace', flavor='mysql')
Maybe Something Else?
I'm considering looking into turning a dataframe into a CSV file and then importing it into the database. Please let me know if you have any clue how to use something like to_sql with SSH.
I ended up using local port forwarding
to solve this problem.
This is what I used in the terminal for local port forwarding:
ssh -N -v SSH_user#SSH_host -L3306:127.0.0.1:3306
I used sqlalchemy for the connection:
from sqlalchemy import create_engine
engine = create_engine("mysql://user:password#127.0.0.1:3306/db?charset=utf8"
df.to_sql(con=engine, name='test_table', if_exists='replace')

Cannot connect to Oracle using python 3.4

I just started to learn python and try to connect to oracle 11g, but I always get following error
cx_Oracle.InternalError: No Oracle error?
Here is my simple script to connect to oracle
import cx_Oracle as oracle
con = oracle.connect('user/password#ip:port/service')
Already try to look for any reference in other sites including here but can't find the solution. I don't think I have connection issue to oracle, because I use the same PC to connect to oracle using PHP.
Any advise would be appreciated, thanks.
One thing to keep in mind anytime you work with Oracle is that they use a proprietary connection protocol TNS (Transparent Network Substrate).
Therefore, you might need to use the cx_Oracle.makedsn(ip, port, SID) method and then pass it to cx_Oracle.connect() method to create your connection. Thus the general format on how to set up Oracle connection is:
import cx_Oracle
ip = 'xxx.xxx.xx.xxx'
port = 'xxxx'
SID = 'SID'
username = 'username'
password = 'password'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect(username, password, dsn_tns)
This is assuming you have already gotten cx_Oracle to work and import properly, which can be finicky depending on your environment.

Categories