How to load pydev data to postgresql - python

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)

Related

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

MYSQL not accepting values from insert statement

So im trying to insert values into a MYSQL database table but the following error keeps on popping up.
would really appreciate some help.
This is my code which i wrote to input a value from a file and store it in a database table.
import mysql.connector
import pickle
try:
connection = mysql.connector.connect(host='localhost',
database='PETROL',
user='Sarthak',
password='q1w2e3r4t5')
cursor = connection.cursor ( )
print(connection)
fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
while True :
try :
pdate = pickle.load (fp1)
cursor.execute("DROP TABLE IF EXISTS DATES")
cursor.execute("CREATE TABLE DATES (ID INT AUTO_INCREMENT PRIMARY KEY,Date DATE)")
cursor.execute ("INSERT INTO DATES(Date) VALUES(pdate)")
cursor.execute("SHOW TABLES")
cursor.commit()
except EOFError :
fp6.close ()
except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))
cursor.close()
connection.close()
The following error keeps on popping up -:
Failed to create table in MySQL: 1054 (42S22): Unknown column 'pdate' in 'field list'
I am not able to encounter what problem is caused by the insert statement which i wrote.
Its better you write your insert statement like this
query = "INSERT INTO DATES(`Date`) VALUES(%s)" cursor.execute (query, pdate)
import pickle
try:
connection = mysql.connector.connect(host='localhost',
database='PETROL',
user='Sarthak',
password='q1w2e3r4t5')
cursor = connection.cursor ( )
print(connection)
fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
while True :
try :
pdate = pickle.load (fp1)
cursor.execute("DROP TABLE IF EXISTS DATES")
cursor.execute("CREATE TABLE DATES (ID INT AUTO_INCREMENT PRIMARY KEY,Date DATE)")
query = "INSERT INTO DATES(`Date`) VALUES(%s)"
cursor.execute (query, pdate)
cursor.execute("SHOW TABLES")
connection.commit() #use connection.commit instead of cursor.commit
except EOFError :
fp6.close ()
except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))
cursor.close()
connection.close()```

pydev data not uploading on postgres

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()

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