Postgresql table update - python

I updated a database table using postgresql from python
My code was
import psycopg2
connection=psycopg2.connect("dbname=homedb user=ria")
cursor=connection.cursor()
l_dict= {'licence_id':1}
cursor.execute("SELECT * FROM im_entry.usr_table")
rows=cursor.fetchall()
for row in rows:
i=i+1
p = findmax(row)
#print p
idn="id"
idn=idn+str(i)
cursor.execute("UPDATE im_entry.pr_table SET (selected_entry) = ('"+p+"') WHERE image_1d ='"+idn+"'")
print 'DATABASE TO PRINT'
cursor.execute("SELECT * FROM im_entry.pr_table")
rows=cursor.fetchall()
for row in rows:
print row
I got the updated table displayed
But when i display updated table by psql as
homedb=# SELECT * FROM im_entry.pr_table;
i got an empty table displayed..what is wrong?? please help me

You're probably not committing the transaction, i.e. you need a connection.commit() after all your updates.
There are various different settings you can make to the isolation level, e.g. autocommit, so you don't need to issue commits yourself. See, for example, How do I do database transactions with psycopg2/python db api?

Related

how to drop all tables in sqlite3 using python?

i made a project which collects data from user and store it on different tables, the application has a delete function which the first option is to delete a specific table which is i already did and the second one is to delete all existing tables.
How can i drop all tables inside my database?
so this is my variables.
conn = sqlite3.connect('main.db')
cursor = conn.execute("DROP TABLE")
cursor.close()
How can i drop all tables inside my database?
According to sqlitetutorial.net
SQLite allows you to drop only one table at a time. To remove multiple
tables, you need to issue multiple DROP TABLE statements.
You can do it by querying all table names (https://www.sqlite.org/faq.html#q7)
Then you can use the result to delete the tables one by one
Here is the code, the function delete_all_tables does that
TABLE_PARAMETER = "{TABLE_PARAMETER}"
DROP_TABLE_SQL = f"DROP TABLE {TABLE_PARAMETER};"
GET_TABLES_SQL = "SELECT name FROM sqlite_schema WHERE type='table';"
def delete_all_tables(con):
tables = get_tables(con)
delete_tables(con, tables)
def get_tables(con):
cur = con.cursor()
cur.execute(GET_TABLES_SQL)
tables = cur.fetchall()
cur.close()
return tables
def delete_tables(con, tables):
cur = con.cursor()
for table, in tables:
sql = DROP_TABLE_SQL.replace(TABLE_PARAMETER, table)
cur.execute(sql)
cur.close()
SQLite3 code to issue multiple DROP TABLE statements based on TEMP_% name wildcard:
.output droptables.sql
SELECT "DROP TABLE """|| sqlite_master.name ||""";" FROM sqlite_master
WHERE type = "table" AND sqlite_master.name LIKE 'TEMP_%';
.read droptables.sql
Example result in .sql output file:
DROP TABLE "TEMP_table1";
DROP TABLE "TEMP_table2";
DROP TABLE "TEMP_table3";
...
Python3 to paste SQL into:
conn = sqlite3.connect(f"main.db")
conn.row_factory = sqlite3.Row
dbc = conn.cursor()
dbc.execute(
f"DROP TABLE 'TEMP_table1';"
)
conn.commit()

SQLite query difficulty

I have a SQLite db with three relational tables. I'm trying to return the max record from a log table along with related columns from the other tables based on the ID relationships.
I created the query in DB Browser and verified it returns the expected record however, when I use the exact same query statement in my python code it never steps into the 'for' loop.
SQL statement in python -
def GetLastLogEntry():
readings = ()
conn = sqlite3.connect(dbName)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT f.FoodCategory, f.FoodName, gs.FoodWeight,
gsl.GrillDateTime, gsl.CurrentGrillTemp, gsl.TargetGrillTemp,
gsl.CurrentFoodTemp, gsl.TargetFoodTemp, gsl.CurrentOutsideTemp,
gsl.CurrentOutsideHumidity FROM Food as f, GrillSession as gs,
GrillSessionLog as gsl WHERE f.FoodId = gs.FoodId AND
gs.GrillSessionID = gsl.GrillSessionID AND gsl.GrillSessionLogID =
(SELECT MAX(GrillSessionLog.GrillSessionLogID) FROM
GrillSessionLog, GrillSession WHERE GrillSessionLog.GrillSessionID
= GrillSession.GrillSessionID AND GrillSession.ActiveSession =
1)")
for row in cursor:
print("In for loop")
readings = readings + (row['FoodCategory'], row['FoodName'])
print("Food Cat = " + row['FoodCategory'])
cursor.close()
return readings
The query in DB Browser returns only one row which is what I'm trying to have happen in the python code.
Just discovered the issue....
Using DB Browser, I updated a record I'm using for testing but failed to "write" the change to the database table. As a result, every time I was executing my python code against the table it was executing the query with the original record values because my change wasn't yet committed via DB Browser.
Huge brain fart on that one.... Hopefully it will be a lesson learned for someone else in the future.

DB browser for sqlite does not work

I write a python code to create a table,but when I open DB browser for SQLite, it does not the table I have created, I am new to database, so can anyone tell me what is wrong with it ? Many thanks!
import sqlite3
conn = sqlite3.connect('test1.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Test''')
cur.execute('''
CREATE TABLE Test (azaz TEXT, count INTEGER)''')
cur.execute('''INSERT INTO Test (azaz, count)
VALUES ( 'aa', 1 )''' )
conn.commit()
conn.close()
image link:imgur.com/epfar.png
Your code is right and if you try:
import sqlite3
conn = sqlite3.connect('test1.sqlite')
row = conn.execute('SELECT * FROM Test').fetchone()
print("azaz=", row[0])
print("count=", row[1])
You will see this output:
('azaz=', u'aa')
('count=', 1)
So the table has been created and values has been inserted in the table.
I have just tested your code and it works flawlessly. I have used python-3.5 and DB Broswer for sqlite, tested on window 7 pro.

Not able to insert into mysql database

I have just started using MySQLdb in python. I am able to create table but when I try to insert, no rows are inserted into the table and its shows that table is still empty.
import MySQLdb
db = MySQLdb.connect("localhost","root","shivam","test")
cursor = db.cursor()
s = "DROP TABLE IF EXISTS batting"
cursor.execute(s)
s = """create table batting (
name varchar(50) primary key,
matches integer(5),
innings integer(5),
runs integer(5),
highest integer(3),
strikerate integer(3),
hundreds integer(3),
fifties integer(3)
)"""
cursor.execute(s)
s = """insert into batting(name) values(
"shivam")"""
cursor.execute(s)
db.close()
Where I could be going wrong?
You forgot to commit your connection. Simply add:
cursor.execute(s)
db.commit()
Have a look at this. It explains why you need to commit

Python write to MySQL - no error but no writing

I am trying to write into my localhost MySQL database.
I have created a database named "test", a table called "price_update" and a row called "model"
When I run the script below I get no errors, however, I also get nothing written to my database.
I am not sure where to start looking for the problem. the row is varchar(10) and collation utf9_general_ci.
import MySQLdb
conn = MySQLdb.connect(host="127.0.0.1",user="someUser",passwd="somePassword",db="test")
query = "INSERT INTO price_update (model) values ('12345')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()
You have to commit the changes:
conn.commit()
Also, I'd make your query safer:
query = "INSERT INTO price_update (model) values (%s)"
...
x.execute(query, ('12345',))

Categories