I tried to use Jupiter notebook to connect MySQL and PostgreSQL. I don't know why it did not work anymore. The error message is "ERROR:root:Internal Python error in the inspect module".
Below is the traceback from this internal error.
In the beginning, I have no problem using sqlite3 to link database
Here is my code using squlite3
pitchfork_db = sqlite3.connect("pitchfork.db")
reviews.to_sql('reviews', pitchfork_db, index=False, if_exists='replace')
artists.to_sql('artists', pitchfork_db, index=False, if_exists='replace')
content.to_sql('content', pitchfork_db, index=False, if_exists='replace')
genres.to_sql('genres', pitchfork_db, index=False, if_exists='replace')
labels.to_sql('labels', pitchfork_db, index=False, if_exists='replace')
years.to_sql('years', pitchfork_db, index=False, if_exists='replace')
I can perform the query I want to
pitchfork_cursor = pitchfork_db.cursor()
pitchfork_cursor.execute("SELECT title, artist, score FROM reviews WHERE
score=10")
colnames = [x[0] for x in pitchfork_cursor.description]
pitchfork_df = pitchfork_cursor.fetchall()
pd.DataFrame(pitchfork_df, columns=colnames)
I got error message using MySQL:
"Traceback (most recent call last):
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it"
Here is my code to MySQL:
import mysql.connector
mysqlpassword = os.getenv("mysqlpassword")
dbserver = mysql.connector.connect(
user='root',
passwd=mysqlpassword,
host="localhost"
)
I got error message using PostgreSQL:
"Traceback (most recent call last):
psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting"
Here is my code to PostgreSQL
import psycopg2
pgpassword = os.getenv("pgpassword")
dbserver = psycopg2.connect(
user='postgres',
password=pgpassword,
host="localhost"
)
dbserver.autocommit = True
I stuck here for several hours, any comments will be great! Thank you!
Related
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.
I'm trying a simple database connection.
"""
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='options',
user='root',
password='xxxxx')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
"""
This works - once - if I uninstall and reinstall MySQL. When I try it a second time if fails to the above Traceback. When it works I've tried a simple read of some of the data. This also works only once per reinstall.
"""
import mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='options',
user='root',
password=xxxxxx)
sql_select_Query = "SELECT command” (my SELECT command is lengthy so I’ve omitted it)
cursor = connection.cursor()
cursor.execute(sql_select_Query)
# get all records
records = cursor.fetchall()
print("Total number of rows in table: ", cursor.rowcount)
print("\nPrinting each row")
for row in records:
print("col1 = ", row[0], )
print("col2 = ", row[1])
print("col3 = ", row[2])
print("col4= ", row[3], "\n")
except mysql.connector.Error as e:
print("Error reading data from MySQL table", e)
finally:
if connection.is_connected():
connection.close()
cursor.close()
print("MySQL connection is closed")
"""
I've done the MySQL installation of the server, workbench, and connector (3x).
I'm using Windows 10 Home with the latest Anaconda release.
Python 3.8.11 (default, Aug 6 2021, 09:57:55) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
I’ve uninstalled ALL mysql entries in the pip list and reinstalled them (multiple times).
I have no issues accessing the database from MySQL Workbench.
(base) PS C:\Users\WARNE> pip list
Package Version
mysql 0.0.3
mysql-connector-python 8.0.26
mysqlclient 2.0.3
(base) PS C:\Users\WARNE> conda install -c anaconda mysql-connector-python
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
…this continued to fail
I've tried about every solution in all of the related questions without any luck. Any help/suggestions would be appreciated.
I finally went back to basics and re-installed, went to very simple code, etc. and this started working. This seems to be a weakness in python-MySQL interworking. This was frustrating.
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'm trying to use sshtunnel and MySQLdb in python2.7 to tunnel my connection and facing following problem:
I used Sequel Pro to connect mysql was OK, but the python code did not work!
Sequel Pro is like this:
connect info
and code is like this:
`from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 22),
ssh_username='name2',
ssh_password='mypassword',
remote_bind_address=('127.0.0.1', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='name1',
password='mypassword',
host='1.1.1.1',
database='mydata',
port=3306)
I searched some example code like:
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
(_host, _ssh_port),
ssh_username=_username,
ssh_password=_password,
remote_bind_address=(_remote_bind_address, _remote_mysql_port),
local_bind_address=(_local_bind_address, _local_mysql_port)
) as tunnel:
connection = MySQLdb.connect(
user=_db_user,
password=_db_password,
host=_local_bind_address,
database=_db_name,
port=_local_mysql_port)
I want to know that did I do the right way to built ssh or connect to mysql? Thanks for help!
update:
the error message:
2017-06-15 17:52:58,415| ERROR | Could not connect to gateway 1.1.1.1:22 : 110
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1483, in __enter__
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1225, in start
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1037, in _raise
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
Update your code to add the local_bind_address:
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 22),
ssh_username='name2',
ssh_password='mypassword',
remote_bind_address=('127.0.0.1', 3306),
local_bind_address = ('1.1.1.1', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='name1',
password='mypassword',
host='1.1.1.1',
database='mydata',
port=3306)
Unless you specify your Localhost (as '1.1.1.1' in your case) & Port; MYSQL service will not be available for the localhost.
I Hope this helps.