pydev data not uploading on postgres - python

My code functions and indentations are correct on eclipse. When running, it displays "Error %s % e" but when I go to postgresql the data doesn't upload there in anyway whatsoever. What should I do?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
con = None
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()

Related

python sqlite3 backup memory db to disk hangs

This script hangs on con.backup:
#!/usr/bin/env python3
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (a INTEGER PRIMARY KEY)")
cur.execute("INSERT INTO t (a) VALUES (NULL)")
bkp = sqlite3.connect('database.db')
con.backup(bkp)
bkp.close()
con.close()
But if I comment the INSERT it works perfectly:
#!/usr/bin/env python3
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (a INTEGER PRIMARY KEY)")
# cur.execute("INSERT INTO t (a) VALUES (NULL)")
bkp = sqlite3.connect('database.db')
con.backup(bkp)
bkp.close()
con.close()
Any idea what I'm doing wrong?

unique values for a duration in mysql

I am new in mysql, I have a table with two cols tag_id and time_stamp, I use a python connector. I need to insert new tag_id just only if did not insert the same tag_id in last 5 min (or some other duration). How can I do that using python mysql.connector?
create table:
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='test',
user='root',
password='root')
mySql_Create_Table_Query = """CREATE TABLE tags (
Id int(11) NOT NULL AUTO_INCREMENT,
tag_id varchar(250) NOT NULL,
time_stamp Datetime NOT NULL,
PRIMARY KEY (Id)) """
cursor = connection.cursor()
result = cursor.execute(mySql_Create_Table_Query)
print("Laptop Table created successfully ")
except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
Insertion function:
def insertVariblesIntoTable(tag, time_stamp):
try:
connection = mysql.connector.connect(host='localhost',
database='test',
user='root',
password='root')
cursor = connection.cursor()
mySql_insert_query = """INSERT INTO tags(tag_id, time_stamp )
VALUES (%s, %s) """
recordTuple = (tag, time_stamp)
cursor.execute(mySql_insert_query, recordTuple)
connection.commit()
print("Record inserted successfully into tags table")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
I'd just do a query of the table like this:
import arrow
check = '''select max(timestamp) from tags where tag_id = {}'''
try:
with conn.cursor() as curs:
curs.execute(check.format(tag_id))
max_time = curs.fetchone()
if max_time <= arrow.utcnow().shift(minutes=-5).format('YYYY-MM-DD HH:mm:ss'):
#run the inserts
else:
pass

How to load pydev data to postgresql

My code functions. When running, it displays "Error %s % e" but when I go to postgresql the data doesn't upload there in anyway whatsoever. What should I do?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
con = None
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()
To start, your code should be formatted like this:
#!/usr/bin/python
-- coding: utf-8 --
import psycopg2
import sys
con = None
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name
VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()
if you're receiving the message "Error ..." then your code is not working as you expect it to. You should break it up into different sections or else manually run these commands in the Python terminal to debug where the issue is. - This is not really an answer, but hopefully we can work this one out since your question has not got enough information for an answer.. try running the following and see which error you hit:
#!/usr/bin/python
-- coding: utf-8 --
import psycopg2
import sys
try:
con = psycopg2.connect("host='localhost' dbname='test123' user='postgres' password='XXX'")
cur = con.cursor()
except Exception:
print("Failed to open a connection")
sys.exit(1)
try:
cur.execute("CREATE TABLE Products(Id INTEGER PRIMARY KEY, Name
VARCHAR(20), Price INT)")
cur.execute("INSERT INTO Products VALUES(1,'Milk',5)")
cur.execute("INSERT INTO Products VALUES(2,'Sugar',7)")
cur.execute("INSERT INTO Products VALUES(3,'Coffee',3)")
cur.execute("INSERT INTO Products VALUES(4,'Bread',5)")
cur.execute("INSERT INTO Products VALUES(5,'Oranges',3)")
con.commit()
except Exception as e:
print("Failed to insert data into the database")
sys.exit(1)

sqlite3 failing to create/insert table

Im doing:
try:
conn = sqlite3.connect('bags_of_coins.db')
print('Db Creation Successful')
except:
print('Db Creation NOT Successful')
try:
conn.execute('''CREATE TABLE bags
(ID INTEGER PRIMARY KEY,
bag TEXT NOT NULL,
);''')
print('Table Creation Successful')
except:
print('Table Creation NOT Successful')
try:
conn.execute("INSERT INTO bags (bag) \
VALUES ('test')");
conn.commit()
except:
print('Insert NOT Successful')
#finally.
conn.close()
But it keeps outputting:
Db Creation Successful
Table Creation NOT Successful
Insert NOT Successful
Does anyone see anything i'm doing wrong? I was following this guide but I cant see to spot the issue. Thanks.
You have comma before ) in this place:
CREATE TABLE bags
(ID INTEGER PRIMARY KEY,
bag TEXT NOT NULL, <- here
);
delete it.
Try this:
import sqlite3
conn = None
try:
conn = sqlite3.connect('bags_of_coins.db')
print('Db Creation Successful')
except:
print('Db Creation NOT Successful')
try:
with conn:
conn.execute("CREATE TABLE bags (ID INTEGER PRIMARY KEY, bag TEXT NOT NULL);")
print('Table Creation Successful')
cursor = conn.execute("INSERT INTO bags (bag) VALUES ('test')")
conn.commit()
print("Insert Successful" if cursor.rowcount > 0 else "Insert NOT Successful")
except:
print('Table Creation NOT Successful')
Your error was creating the table.
The 'with' is a plus I added, it takes care of closing the connection when the block finish by any reason so you don't need the 'finally' block.
Don't hesitate to ask if you have any doubt.
Blindly banging out try..except without showing the error from the exception is just going to cause you grief and heartache, use the exception available to list the specific error.
import sqlite3
try:
conn = sqlite3.connect('bags_of_coins.db')
except sqlite3.Error as e:
print('Db Creation NOT Successful', str(e))
mycursor = conn.cursor()
try:
mycursor.execute("CREATE TABLE bags (ID INTEGER PRIMARY KEY,bag TEXT NOT NULL)")
except sqlite3.Error as e:
print("Table creation failed", str(e))
try:
mycursor.execute("insert into bags (bag) values (?)", (['test']))
conn.commit()
except sqlite3.Error as e:
print("table insert failed", str(e))
#finally.
conn.close()

Python+mysql - building insert statements in for loop

The following prints the results properly but no records show up in the mysql table I'm attempting to populate:
#!/usr/bin/python
import MySQLdb
import string
db = MySQLdb.connect(host="localhost",
user="user",
passwd="******",
db="test")
cur=db.cursor()
i = 0
for lt in string.ascii_lowercase:
dbinsert = """insert into dns(domain,A,MX,T,serial,ttl)
values('"""+lt+""".com',' 1.1.1."""+str(i)+"""\\n','10 mx1.somehost.com.\\n',
'# "txt data"\\n',2013092001,300)"""
print dbinsert
i+=1
#cur=db.cursor()
try:
cur.execute(dbinsert)
db.commit
except MySQLdb.Error, e:
print e[0], e[1]
db.rollback()
db.close()
What am I missing here?
db.commit should be db.commit()

Categories