I am trying to connect to my database via Python 2.7 with this code:
import csv
import psycopg2
try:
conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
cursor = conn_cursor()
reader = csv.reader(open('last_file.csv', 'rb'))
print "connected"
except:
print "not Connected"
It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.
import psycopg2
try:
conn = psycopg2.connect("dbname='database_name' user='postgres_user_name' host='localhost' password='user_passwd'")
except:
print "I am unable to connect to the database"
cur = conn.cursor()
cur.execute("""SELECT * from table_name""")
rows = cur.fetchall()
print "\nShow me the data:\n"
for row in rows:
print " ", row[0]
print " ", row[1]
Exception part add like this to see what is error
except Exception as ex:
print "not Connected"
print "Error: "+ str(ex)
Try this:
import csv
import psycopg2
try:
conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
except:
print "I am unable to connect to the database."
cursor = conn.cursor()
try:
reader = csv.reader(open('last_file.csv', 'rb'))
print "connected"
except:
print "not Connected"
Seems like there are something wrong with your postgres.
Try and see postgres log.
Location of postgres log by default :
tail -f /var/log/postgresql/<>/main/postgresql.log
something like this.
Also don't forget to check firewall. Maybe someone disable it by accident.
Also try for pip install PyGreSQL package. Since psycopg2 (some of versions) is under GPL license. It could be tricky for open source license. Just for your information.
Related
I would like to ask how can I declare the variable "mobile" on the sql query?
I can print the mobile using .format() but it ain't working on the query cur.execute(). How should I declare the "mobile" variable for the query to update my database?
Also for your information I have a text file which named currentNum.txt and the only value inside is 639662146331(please take note that this should a string)
Thank you in advance!
import psycopg2
import os
try:
conn = psycopg2.connect("dbname='database' user='postgres' password='password'")
print("Connected to database.")
except:
print("Unable to connect to database.")
cur = conn.cursor()
try:
list=open("currentNum.txt", "r")
mobile=list.readline()
# It doesn't update the database
cur.execute("UPDATE notif_counter SET status='Notify' WHERE mobile='{0}'".format(mobile))
conn.commit();
# This is working
print("Table notif_counter where mobile {0} successfully updated.".format(mobile))
list.close()
except:
print("Failed to update the table for notif_counter")
finally:
if(conn):
cur.close()
conn.close()
print("PostgreSQL connection is closed.")
list = open("input.txt",'r')
mobile = list.readline().strip()
cur.execute("UPDATE notif_counter SET status='Notify' WHERE mobile='{}'".format(mobile))
it looks like you have forgot to remove trailing whitespace, use .strip()
Relatively new to python scripts, so bare with.
I have used speedtest-cli before. I have edited the script so it will insert the values into a sql table as below, however having an issue with one of the inserts. It will insert ping, and download ok, however, the upload is always 2.74 or 2.75 for example, but ONLY when run from a crontab.. very weird.
If I run the python script from cli it will insert values fine.
This is my query, and the values ping, download and upload are coming from the speedtest-cli script.
Here is the full script
import re
import subprocess
import time
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
print "----------------------------------"
print 'Started: {} {}'.format(time.strftime('%d/%m/%y %H:%M:%S'), "")
response = subprocess.Popen('speedtest-cli --simple', shell=True, stdout=subprocess.PIPE).stdout.read()
ping = re.findall('Ping:\s(.*?)\s', response, re.MULTILINE)
download = re.findall('Download:\s(.*?)\s', response, re.MULTILINE)
upload = re.findall('Upload:\s(.*?)\s', response, re.MULTILINE)
ping[0] = ping[0].replace(',', '.')
download[0] = download[0].replace(',', '.')
upload[0] = upload[0].replace(',', '.')
try:
if os.stat('/var/www/html/speed/log.txt').st_size == 0:
print 'Date,Time,Ping (ms),Download (Mbit/s),Upload (Mbit/s)'
except:
pass
print 'PING: {}, DOWN: {}, UP: {}'.format(ping[0], download[0], upload[0])
try:
connection = mysql.connector.connect(host='localhost',
database='dev',
user='dev',
password='dev1')
sql_insert_query = ("""INSERT INTO speedtest(ping, download, upload) VALUES (%s,%s,%s)""", (ping[0], download[0], upload[0]))
cursor = connection.cursor()
result = cursor.execute(*sql_insert_query)
connection.commit()
print ("Insert success into speedtest tbl")
except mysql.connector.Error as error :
connection.rollback() #rollback if any exception occured
print("Failed inserting record into speedtest table {}".format(error))
finally:
#closing database connection.
if(connection.is_connected()):
cursor.close()
connection.close()
print("MySQL conn closed")
print 'Finished: {} {}'.format(time.strftime('%d/%m/%y %H:%M:%S'), "")
Manual script runs ok, just from crontab I get unexpected values. Not sure how to solve.
I would like to put a button on the GUI if the software connects to a specific Postgre-DB. I wrote a small test-function: if it can connect to the DB it returns True, if not it returns False.
The code works, but there is an issue: if there is no connection (I just pull out the internet cable, nothing else changes), it simply
takes too much time.
Could you help me to make the code faster if there is no connection?
Here is my simple test-function:
import psycopg2
def postgres_test():
try:
conn = psycopg2.connect("dbname='mydb' user='myuser' host='my_ip' password='mypassword'")
conn.close()
return True
except:
return False
Thanks for the comments. And yes, it was timeout related.
Here is my faster code:
import psycopg2
def postgres_test():
try:
conn = psycopg2.connect("dbname='mydb' user='myuser' host='my_ip' password='mypassword' connect_timeout=1 ")
conn.close()
return True
except:
return False
For test postgres connection with python first you have to install this package :
pip install psycopg2-binary
and try this code :
import psycopg2
conn = psycopg2.connect(dbname="db_name",
user="user_name",
host="127.0.0.1",
password="******",
port="5432")
cursor = conn.cursor()
cursor.execute('SELECT * FROM information_schema.tables')
rows = cursor.fetchall()
for table in rows:
print(table)
conn.close()
there’s something wrong in my python script: when I try to put some data in my database and print it, it looks like it’s working, but when I rerun the code, or if I check the phpmyadmin, there’s no data saved in the db. Does anyone have some idea on how to solve this problem?
import mysql.connector
from mysql.connector import errorcode
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='Temperature',
user='Temperature',
password='mypass')
if conn.is_connected():
print('Connected to MySQL database')
cur = conn.cursor()
query = "INSERT INTO Temp(temp, humi) " \
"VALUES(315, 55)"
try:
cur.execute(query)
except MySQLdb.ProgrammingError as e:
print(e)
query = "SELECT * FROM Temp"
try:
cur.execute(query)
for reading in cur.fetchall():
print (str(reading[0])+" "+str(reading[1]))
except MySQLdb.ProgrammingError as e:
print(e)
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
You will need to add conn.commit() before conn.close(). That should solve the problem.
I am trying to connect to a remote postgreSQL database, using the following code:
import psycopg2
try:
# this:
conn = psycopg2.connect(database="A B C", user="user", password="pass", host="yyyy.xxxxx.com", port= 5432)
# or this:
conn = psycopg2.connect("dbname=A B C user=user password=pass host=yyyy.xxxxx.com port=5432")
# or this:
conn = psycopg2.connect("dbname='A B C' user='user' password='pass' host='yyyy.xxxxx.com' port=5432")
print "connected"
except psycopg2.Error as e:
print "I am unable to connect to the database"
print e.pgcode
print e.pgerror
So if I am sure I have the correct database name, which has spaces in it like "A B C" in my example, and the correct username/password/host/port, why can I not connect? Also, why does no error get passed onto the exception handler? I am using python 2.7.9. Here is the output, which is the same for any of the psycopg2.connect statements:
I am unable to connect to the database
None
None
You should see more info in e exception and also use very useful traceback module:
import traceback
...
except psycopg2.Error as e:
print "I am unable to connect to the database"
print e
print e.pgcode
print e.pgerror
print traceback.format_exc()