Database is not reachable - pymysql - python

After reading many thread here i didn't resolved my problem, my code works with a free database created in this website (freemysqlhosting.net), but it doesn't work with my own database on a hosting webiste. My code ('******' for privacy):
#!/usr/bin/python3
import pymysql
db = pymysql.connect("sql.******.it", "******", "******", "******")
cursor = db.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
print(results)
db.close()
Here the error:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'sql.******.it' ([Errno 101] Network is unreachable)")

From command line I would use ping, and then nc. I mean, just cut things to minimum, an check if that works. So first validate if host is valid, and your host can resolve it to IP. Next check if you can connect to that host, on provided port. Here is sample in python.
If I have to bet - I would say, you are missing port... Just double check all names, docs provided by the hosting.

Have you tried using mysql.connector? That's what I use maybe it will work
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)

Related

How do I connect a Python program in Visual Studio Code to MySQL Workbench 8.0?

I am creating a program that uses VS Code and MySQL Workbench 8.0 together. I am stuck and do not know how to connect the two software together
I also have to be able to upload records into a table that is stored in MySQL Workbench from the Python program that uses variables.
Please tell me if their are any details missing.
Thank you.
For connection:
I have researched on Google and have been unable to find an answer. I have found that I have to install certain packages and use the connect method. However, I do not know the parameters of the connect function.
For uploading data into table:
I have found that I have to create a cursor to somehow upload the data to the table, but am unsusre of the full details.
There are many packages in python that can connect to the mysql database, here we take pymysql as an example.
Install pymysql
pip install PyMySQL
I have already installed, so the prompt package already exists.
Sample code, query and insert data
import pymysql
con = pymysql.Connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='test',
charset='utf8'
)
cur = con.cursor()
sql1 = 'select * from student'
cur.execute(sql1)
data = cur.fetchall()
cur.close()
con.close()
for i in data:
print(str(i))
Add an insert data statement, and re-query after inserting data.
import pymysql
con = pymysql.Connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='test',
charset='utf8'
)
cur = con.cursor()
sql2 = 'insert into student values("002","jerry","W");'
cur.execute(sql2)
sql1 = 'select * from student'
cur.execute(sql1)
data = cur.fetchall()
con.commit()
cur.close()
con.close()
for i in data:
print(str(i))

MySQL connection with Python through PythonAnywhere

I want to connect to MySql database using Python through PythonAnywhere, without creating a Flask/Django application.
I have seemingly managed to connect through MySQLdb, using the code below, but I do not receive a response when I run the code. Any solutions?
import MySQLdb
db = MySQLdb.connect(
host = "myuser.mysql.pythonanywhere-services.com",
user = "myuser",
passwd = XXX,
db = "myuser$db_name"
)
cursor = db.cursor()
cursor.execute("SELECT * FROM table_name")
for x in cursor:
print(x)
cursor.close()
db.close()
You retrieve all rows in the table, without error.
cursor.execute("SELECT * FROM table_name")
for x in cursor:
print(x)
Yet you see no output. This is normal for a table that contains zero rows.
Consider doing one or more INSERTs, and a COMMIT,
prior to the query.

Issues connecting to PythonAnywhere SQL Server

I'm trying to create a table in mySQL server running on pythonAnywhere from my local machine.
I followed the getting started guide, https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere, but I'm running into a OperationalError: (2013, 'Lost connection to MySQL server during query').
Here is my code:
import MySQLdb
import sshtunnel
sshtunnel.SSH_TIMEOUT = 10
sshtunnel.TUNNEL_TIMEOUT = 10
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='MyUSERNAME', ssh_password='***',
remote_bind_address=('MyUSERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='MyUSERNAME',
passwd='***',
host='127.0.0.1', port=tunnel.local_bind_port,
db='MyUSERNAME$liveSports',
)
cur = connection.cursor()
with connection:
cur.execute("CREATE TABLE table_one (date TEXT, start_time TEXT)")
I'm not sure why I'm getting this error, or how to resolve it.
Similar errors, Lost connection to MySQL server during query , suggest that either I'm sending an incorrect query to my server, but as far as I know this is a valid query, or that my packet is too large, which I don't believe an empty table would be.
I'm new to SQL, but I can't seem to find an answer to this question.
You must leave the tunnel open. This is the easy way:
import MySQLdb
import sshtunnel
sshtunnel.SSH_TIMEOUT = 10
sshtunnel.TUNNEL_TIMEOUT = 10
tunnel = sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='MyUSERNAME', ssh_password='***',
remote_bind_address=('MyUSERNAME.mysql.pythonanywhere-services.com', 3306)
)
connection = MySQLdb.connect(
user='MyUSERNAME',
passwd='***',
host='127.0.0.1', port=tunnel.local_bind_port,
db='MyUSERNAME$liveSports',
)
cur = connection.cursor()
cur.execute("CREATE TABLE table_one (date TEXT, start_time TEXT)")
You could put all of your database stuff in a function and use
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='MyUSERNAME', ssh_password='***',
remote_bind_address=('MyUSERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
do_all_processing()
def do_all_processing():
connection = MySQLdb.connect(
user='MyUSERNAME',
passwd='***',
host='127.0.0.1', port=tunnel.local_bind_port,
db='MyUSERNAME$liveSports',
)
...etc...

Python update query in mariadb

I am trying to update my mariadb table via python code .While compile the query nothing happen in my database. please check below code and let me know where i made mistake in update function
import mariadb
connection= mariadb.connect(user="user1", database="db1", host="ippp" ,password="pass")
cursor= connection.cursor()
cursor.execute("UPDATE product_options_combinations SET quantity=5944 WHERE item_code ='31628'")
cursor.close()
connection.close()
Hello here I have a clean code example for you. How to update it.
import pymysql
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"
# User name of the database server
User = "user"
# Password for the database user
Password = ""
database = "GFG"
conn = pymysql.connect(host=Host, user=User, password=Password, database)
# Create a cursor object
cur = conn.cursor()
query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'"
cur.execute(query)
#To commit the changes
conn.commit()
conn.close()
You just need to add connection.commit() to your code, but I recommend you use a parametrized SQL preferably with a list of tuples,more of which might be added if needed, along with cursor.executemany() as being more performant for DML statements such as
import mariadb
connection= mariadb.connect(user="user1",
password="pass",
host="ippp",
port=3306,
database="db1")
cursor= connection.cursor()
dml="""
UPDATE product_options_combinations
SET quantity=%s
WHERE item_code =%s
"""
val=[
(5944,'31628')
]
cursor.executemany(dml,val)
connection.commit()
cursor.close()
connection.close()
Are you sure that the connection is working properly?
Have you tried to implement a try and catch routine to print mariadb errors?
Something like this:
# Connect to MariaDB Platform
import mariadb
try:
conn = mariadb.connect(
user="user",
password="password",
host="xx.xx.xx.xx",
port=3306,
database="db_name"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)

PyMySQL using localhost vs socket incoherant behaviour

I am using PyMySQL to connect to a database running on localhost. I can access the database just fine using the username/password combiunation in both the command line and adminer so the database does not appear to be the probem here.
My code is as follow. However, when using the host="127.0.0.1" options, I get an OperationalError and an Errno 111. Using the same code, but connecting via the socket Mariadb runs on is fine.
import pymysql.cursors
from pprint import pprint
# This causes an OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
# connection = pymysql.connect(
# host="127.0.0.1",
# port=3306,
# user="root",
# password="S3kr37",
# db="my_test",
# )
# This works.
connection = pymysql.connect(
user="root",
password="S3kr37",
db="my_test",
unix_socket="/var/lib/mysql/mysql.sock"
)
try:
with connection.cursor() as cursor:
sql = "select * from MySuperTable"
cursor.execute(sql)
results = cursor.fetchall()
pprint(results)
finally:
connection.close()
What am I doing wrong?
PS: Note that this question has the same problem but the solution offered is the socket. That is no good enough: I want to know why I cannot use the hostname as the documentation suggests.
Errorcode 2003 (CR_CONN_HOST_ERROR) is returned by the client library, in case the client wasn't able to establish a tcp connection to the server.
First you should check, if you can connect via telnet or mysql command line client to your server.
If not, check the server configuration file:
does the server run on port 3306?
is IPv4 disabled?
is skip-networking enabled?
is bind-address activated (with another IP?

Categories

Resources