I am trying to connect to my pythonanywhere DB from a local python file, using the following code.
import MySQLdb, sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
queryAdd = ("INSERT INTO `****$geo***`.O***"
"(name, address) "
"VALUES (%s, %s)")
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='*******', ssh_password='*******',
remote_bind_address=('*****.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='******',
passwd='********',
host='127.0.0.1', port=tunnel.local_bind_port,
db='****$geo******',
)
cursor = connection.cursor()
for row in dl:
tup=(row['name'],row['address'])
cursor.execute(queryAdd, tup)
connection.commit()
However, as soon as the code is run, I get the following error:
MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
There is no delay between creating the connection and running the query. What am I doing wrong?
You need to do everything inside your with block as the tunnel is gone when you go outside of the context.
Related
I am trying to connect to a MySQL database using mysql.connector:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
password="password",
database="database"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM table")
myresult = mycursor.fetchone()
print(myresult)
I get this error message:
errno=2003, values=(self.get_address(), _strioerror(err)))
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)
Does this mean that there something wrong with the database credentials?
I'm using Anaconda and python3.7 and I'm trying to connect to a remote database using the following code:
import MySQLdb
myDB = MySQLdb.connect(host="xxxxx", port=3306, user="xxx",password="xxxx",db="xxxx")
but I get the following error:
File "C:\Users\zanto\anaconda3\lib\site-packages\MySQLdb\connections.py", line 208, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2006, 'SSL connection error: unknown error number')
I tried 2 users in mysql one using % and one using localhost but I still get the same error.
It was a problem of mySQLdb library.
I installed pymysql library through anaconda and now it's working!
My new code is:
import pymysql.cursors
connection = pymysql.connect(host='xxxx',port=3306,user="xxxx",password="xxxx",db="xxxx", cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql="SELECT * FROM Table WHERE Field = 'value'"
cursor.execute(sql)
results = cursor.fetchall()
#print (results) #if you remove the comment you will get the query result as a dictionary
for record in results:
record_line = " ".join('{0}{1}'.format(field,value) for field,value in record.items())
print(record_line)
finally:
connection.close()
More info: A cursor allows Python code to execute MySQL command in a database session. A cursor is created by the connection.cursor() method: they are bound to the connection for the entire lifetime and all the commands are executed in the context of the
database session wrapped by the connection.
The cursor.execute() method runs a query in MySQL database. The cursor.fetchall() method returns the results of a query in list form that contains the records as dictionaries.
I am trying to connect to a MySQL database hosted on Python Anywhere. In the below example connection.get_server_info() returns a result however connection.is_connected() returns False and I am unsure why.
Here is my code:
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USERNAME', ssh_password='PASSWORD',
remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='USERNAME', password='DB_PASSWORD',
host='127.0.0.1', port=tunnel.local_bind_port,
database='USERNAME$default',
)
db_info = connection.get_server_info()
if connection.is_connected():
print('Connected to MySQL DB...version on ', db_info)
else:
print('Failed to connect.')
print(db_info)
connection.close()
I have a paid account on Python Anywhere so SSH tunneling should be possible
It's because you're trying to access the SSH tunnel after it has been closed; the tunnel is closed when you exit the with block, so anything that uses the connection needs to be indented so that it is contained within it. Your code above look like this:
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USERNAME', ssh_password='PASSWORD',
remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='USERNAME', password='DB_PASSWORD',
host='127.0.0.1', port=tunnel.local_bind_port,
database='USERNAME$default',
)
db_info = connection.get_server_info()
if connection.is_connected():
print('Connected to MySQL DB...version on ', db_info)
else:
print('Failed to connect.')
print(db_info)
connection.close()
I am facing problem while inserting data in my live database server. My current connection code is:
import pymysql
host="192.224.256.***"
user_name="user"
password= "pass"
database="checkDatabase"
try:
connection = pymysql.connect(host, user_name, password, database)
print("connection established")
except:
print("connection failed")
result is :: connection failed..
Is there any way that I can connect to my live database server and insert data into it?
You should connect like this :
connection = pymysql.connect(host='localhost', port=3306, user='user', passwd='password', db='database')
Or like this :
db_name = "database"
db = pymysql.connect("localhost", "user", "password", "db_name")
Eather way you need the quotes so you cant just add strings the way you did it.
When I run
library(RMySQL)
mydb = dbConnect(MySQL(), user = "XX", password = "XX", dbname = "XX", host = "XX")
on the R console it works,
however when I put save it as a yy.R file and run it as R CMD BATCH yy.R, or as source("yy.R") it says
Error in mysqlNewConnection(drv, ...) :
RS-DBI driver: (Failed to connect to database: Error: Can't connect to MySQL server on 'XX' (111)
)
Calls: dbConnect -> dbConnect -> mysqlNewConnection -> .Call
Execution halted
could I check if RMySQL only runs on the console? Thanks!
Perhaps you can specify the driver with RMySQL::MySQL(), this works for me in scripts.