how can I connect to a postgresql database from external psycopg2.connect? - python

I would like to connect to a postgresql database using python from a different server.
I triyed this :
conn_string = "host=192.168.1.1 dbname='"+db7+"' user='user' password='"+pw7+"'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
but I get the error:
conn = psycopg2.connect(conn_string)
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL: database "database" does not exist

Remove unnecessary quotes in the syntax.
Follow this structure.
conn = psycopg2.connect(host = "localhost",database="ur_database_name", user="db_user", password="your_password")
Example.
conn = psycopg2.connect(host = "localhost",database="studentesdb", user="postgres", password="admin")

Related

SQL connection string into function

I am trying to put a connection string into a function for database connection:
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server=trve-tl'
'Database=team;'
'Trusted_Connection=yes;')
with open("bike.sql", "r") as file:
query = file.read()
I have attempted to create a function as follows:
def get_connection(server:str, Database:str)->str:
global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server='+server+';'
'Database='+Database+';'
'Trusted_Connection=yes;')
return conn
I get the following error:
global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
^
SyntaxError: invalid syntax
You need to remove the 'global' keyword from your conn variable declaration, then store the output of the function in a new variable.
def get_connection(server:str, Database:str)->str:
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server='+server+';'
'Database='+Database+';'
'Trusted_Connection=yes;')
return conn
then call it something like this
cn = get_connection("localhost","MyDB")
cn.close()

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...

Connect to MySQL on GCE using Google Colaboratory

I am trying to access MySQL on GCE VM instance through Google Colaboratory though, unfortunately, it does not work properly but does work in the local VSCode environment.
While executing TestExec.py, it shows SSH Connected so it seems that ssh connection is successfully done though, however, it seems to be stuck on MySQL connection.
Output on Google Colab:
Please help with the solutions/tips?
sqlList = []
sqlList.append("select * from table name;")
HOST = 'ComputeEngine PublicIP'
PORT = 22
USER = 'username'
DBUSER = 'username for db'
KEY_FILE = 'private key file path'
DBNAME = 'dbname'
DBPORT = 3306
SSH_BASTION_ADDRESS = HOST
SSH_PORT = PORT
SSH_USER = USER
SSH_PKEY_PATH = KEY_FILE
MYSQL_HOST = HOST
MYSQL_PORT = 3306
MYSQL_USER = DBUSER
MYSQL_PASS = 'MySQL Login PW'
MYSQL_DB = DBNAME
with SSHTunnelForwarder(
(SSH_BASTION_ADDRESS, SSH_PORT),
ssh_pkey=SSH_PKEY_PATH,
ssh_username=SSH_USER,
# ssh_password=PASSPHRASE,
remote_bind_address=('localhost', MYSQL_PORT),
local_bind_address=('localhost', MYSQL_PORT)
) as ssh:
print("SSH Connected")
print(ssh.local_bind_port)
try:
connection = mysql.connector.connect(
host='localhost',
port = ssh.local_bind_port,
user=MYSQL_USER,
passwd=MYSQL_PASS,
db=MYSQL_DB,
charset='utf8'
)
print(connection.is_connected())
print("DB Connected")
cur = connection.cursor()
sql = "use dbname"
cur.execute(sql)
# rows = cur.fetchall()
# for row in rows:
# print(row)
for i in range(len(sqlList)):
print(sqlList[i])
sql = str(sqlList[i])
# sql = 'create table test (id int, content varchar(32))'
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
print(row)
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
connection.rollback()
raise err
finally:
cur.close()
connection.commit()
connection.close()
It seemed the error occurred because of the connection. I have changed the method of connection.
import pymysql.cursors
connection = pymysql.connect(
host='localhost',
user='user',
password='password!',
db='dbname',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)

Unable to connect to postgres database with psycopg2

I am trying to connect to psql server but unfortunately always receiving this error. (windows, vs code, python 3.7.4, psycopg2, postgresql 11)
Code part:
import psycopg2
import json
data = json.load(open("data.json"))
conn = psycopg2.connect(database = "dictfly", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432")
print("Opened database successfully")
cur = conn.cursor()
for pair in data:
cur.execute("ISERT INTO dict_tables VALUES (pair, data[pair])")
conn.commit()
print("Records created successfully")
conn.close()
Terminal
PS C:\mysite\dict> python jsonTOpgsql.py
Traceback (most recent call last):
File "jsonTOpgsql.py", line 6, in <module>
conn = psycopg2.connect(database = "dictfly", user = "postgres", password = "postgres0208", host = "127.0.0.1", port = "5432")
File "C:\Users\uafir\AppData\Local\Programs\Python\Python37-32\lib\site-packages\psycopg2\__init__.py", line 126, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError
PS C:\mysite\dict>
Thank you in advance!
I believe 'database' is not a valid keyword argument for psycopg2.connect(). Try using the keyword 'dbname' instead:
conn = psycopg2.connect(dbname="dictfly", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432")
Source: psycopg2 documentation

Python script unable to connect to MySQL db with no password

I am having a weird issue with my python script. My script has to connect to MySQL DB. This is the code:
try:
conn = MySQLdb.connect( user='root', host = 'localhost')
cursor = conn.cursor()
databases = cursor.fetchall()
cursor.close()
except Exception as e:
print e
when I run this script I have and error like:
(1045, "Access denied for user 'root'#'localhost' (using password: NO")
in the other hand, I can connect to MySQL just by entering MySQL (without password).
Why am I having this error with my python script when there is no password to root user?
Provide empty password
try this
conn = MySQLdb.connect( user='root', host = 'localhost', passwd='')
This should be the syntax. You should have the MySql connector for Python
import mysql.connector
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='database_name')
cnx.close()
try this (inside the bloc try except)
import mysql.connector
conn = mysql.connector.connect(user='root', password='',host='localhost',
database='your_database_name')
conn.close()

Categories

Resources