A database is not being created in python PostgreSQL - python

import psycopg2
from config import host, user, password, db_name, port
connection = None
try:
# подключаемся к базе
connection = psycopg2.connect(
host=host,
user=user,
password=password,
database=db_name,
port=port
)
connection.autocommit = True
# cursor нужен чтобы взаимодействовать с БД
# сейчас создаем нашу БД
with connection.cursor() as cursor:
cursor.execute(
"""CREATE TABLE IF NOT EXISTS data1 (
price int NOT NULL,
styles text NOT NULL,
runes text);"""
)
except Exception as _ex:
print("[INFO] Error while working with PostgreSQL", _ex)
finally:
if connection:
connection.close()
print("[INFO] PostgreSQL connection closed")
config
host = "127.0.0.1"
user = "postgres"
password = "14101999"
db_name = "data"
port = "5432"
When executing , it outputs [INFO] Error while working with PostgreSQL
I do not understand at all what the problem is and why the database is not being created, I seem to have indicated everything correctly in config...

I don't see where you are creating a database. psycopg2.connect() has to connect to an existing database. So either you create the database outside the Python script or you connect to an existing database, best practices the database named postgres, and then issue a CREATE DATABASE <some_name>. You would then need to close the existing connection and create a new one to the new database.

Related

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'l ocalhost:3306' (111 Connection refused)

I am using mysql connect in the python script.
Python script needs to work for long time
It works fine for a few hours but it has issues to connect mysql after some hours
Here is my codes.
Code to connect mysql
host = "localhost"
user = "root"
def get_connection():
connection = mysql.connector.connect(
host=host,
user=user,
password=password,
database=database
)
return connection
Script repeats below codes to insert the results
connection = get_connection()
cursor = connection.cursor()
cursor.executemany(insert_query, records_to_insert)
connection.commit()
posts = cursor.rowcount + 1
cursor.execute("""UPDATE topics set posts=%s WHERE tid=%s""", (posts, topic_id, ))
connection.commit()
cursor.close()
connection.close()
Could you give me a solution to resolve my issues?
Thanks.

psycopg2 - use the same database instance connection to read data from multiple databases

I have one database instance that has multiple databases. The database instance is a Postgres AWS RDS instance.
My goal is to select data from multiple databases using the same DB connection.
This is an example of my database connection handler:
class BMR_Connection:
"""connect to BMRS db to get past messeges"""
def __init__(self):
# connect to the database
self.connection = psycopg2.connect(
dbname=config.dbname1,
user=config.user,
password=config.password,
host=config.host,
)
self.connection.autocommit = True
self.cursor = self.connection.cursor()
def get_data(self):
sql_command = """
SELECT *
from public.datatable1
"""
self.cursor.execute(sql_command)
rows = self.cursor.fetchall()
And I have three similar database connection handler classes
BMS_Connection
BMT_Connection
BMU_Connection
that are connecting to the same database instance config.host, using the same username config.user and password config.password , But picking data from different databases of that instance like
config.dbname2
config.dbname3
config.dbname4
Is there a way I can establish a connection to the database instance and then specify the database I want to read data from in sql queries?
By doing that, I would only specify host name during connection
self.connection = psycopg2.connect(
user=config.user,
password=config.password,
host=config.host,
)
And then specify the database name in SQL queries
sql_command = f"""
FROM DATABASE {dbname1}
SELECT *
from public.datatable1
"""

Python mysqldb stops working after trying to connect to DB

I'm trying to connect to a external database but after trying to connect to the database, the whole script stops running. i'm trying to run it on a Raspberry PI 3. So after the attempt to connect to the database, it stops working. the test print does show up but the second one does not.
Script:
import MySQLdb
HOST = "host"
PORT = 3306
USER = "user"
PASS = "pass"
DATABASE = "databasename"
print("test")
db = MySQLdb.connect(HOST, USER, PASS, DATABASE)
print("test2")
cursor = db.cursor()
cursor.execute("SELECT * FROM Persoon")
data = cursor.fetchone()
print "database version :%s"% data
db.close()

general connection to a mysql server

Is there a way to make a general connection to a mysql server and not specifically to any one of its databases? I found the following code snippet. The connect method connects to a specific database called employees.
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees')
cnx.close()
Yes, You can make the same connection without specifying the database name:
cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1')
It would be the same as connecting from the terminal using:
mysql -h 127.0.0.1 -u scott -ptiger
Note: 127.0.0.1 is your localhost.
Also, I usually do not store the actual connection information in the script. I would do something more like this (If you can):
def CloseConnection(cnxIn, cursorIn):
cursorIn.close()
cnxIn.close
return
user = input('Enter your user name: ')
user = user.strip()
password = getpass.getpass()
host = input('Enter the host name: ')
host = host.strip()
cnx = mysql.connector.connect(user=user, password=password, host=host)
cursor = cnx.cursor(buffered=True)
cursor.execute ('select VERSION()')
row = cursor.fetchone()
CloseConnection(cnx, cursor)

Got an error while connecting to database

I am unable to connected to database in linux using psycopg2. I have postgresql installed in linux and my code is:
import psycopg2
def testEgg():
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
cur = conn.cursor()
cur.execute("CREATE TABLE egg ( num integer, data varchar);")
cur.execute("INSERT INTO egg values ( 1, 'A');")
conn.commit()
cur.execute("SELECT num from egg;")
row = cur.fetchone()
print row
cur.close()
conn.close()
testEgg()
And the I got the error:
psycopg2.OperationalError: FATAL: Ident authentication failed for user "postgres"
This code runs well in windows7 but got above mentioned error in linux.
Is there anything I need to do more in linux? Any suggestion will be appreciated.
Thank you.
It's not a problem due to your code, but due to the permission of the postgres user.
You should create a new user to access to your database and replace this :
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
by (replace <your_user> by your real user name ...)
conn = psycopg2.connect("dbname = myDatabase user = <your_user> port = 5432")
To create a new user on postgres, you can use the 'createuser' binary. The documentation is available here.

Categories