q = "update student set mark=mark+5 WHERE id =7"
r_set = my_conn.execute(q)
print("Records updated")
Explore interactive code cells, execute parameterized UPDATE queries, test error handling, and run Pandas bulk upsert operations directly in Google Colab.
View on GitHubq = "UPDATE student set class='Five' WHERE class='Four' "
try:
r_set = my_conn.execute(q)
print("Records updated")
except sqlite3.Error as my_error:
print("error: ", my_error)
Output
Records updated
print(r_set.rowcount) # 9
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("sqlite:///my_db.db")
try:
with my_conn.begin() as connection:
q = text("UPDATE student set mark=mark+1")
r_set = connection.execute(q)
print("No of records updated : ", r_set.rowcount)
except SQLAlchemyError as e:
print(e)
my_data = ('Seven', 'Six') # tuple to pass values to execute method
q = "UPDATE student set class=? WHERE class=? "
try:
r_set = my_conn.execute(q, my_data)
print("Records updated : ", r_set.rowcount)
except sqlite3.Error as my_error:
print("error: ", my_error)
Output
Records updated : 1
Updating single records
q = "update student set mark=mark+5 WHERE id =9"
r_set = my_conn.execute(q)
print("Records updated : ", r_set.rowcount)
Output
Records updated : 1
import pandas as pd
from sqlalchemy import create_engine, text
my_conn = create_engine("sqlite:///my_db.db")
# Prepare update dataset inside Pandas
df_update = pd.DataFrame({
'id': [1, 2, 3],
'name': ['John Deo', 'Max Ruin', 'Arnold'],
'class': ['Five', 'Six', 'Four'],
'mark': [80, 90, 65],
'gender': ['female', 'male', 'male']
})
with my_conn.begin() as conn:
df_update.to_sql('temp_student', conn, if_exists='replace', index=False)
upsert_sql = text("""
INSERT INTO student (id, name, class, mark, gender)
SELECT id, name, class, mark, gender FROM temp_student
ON CONFLICT(id) DO UPDATE SET
name = excluded.name,
class = excluded.class,
mark = excluded.mark,
gender = excluded.gender;
""")
conn.execute(upsert_sql)
conn.execute(text("DROP TABLE temp_student"))
Explore interactive code cells, execute parameterized UPDATE queries, test error handling, and run Pandas bulk upsert operations directly in Google Colab.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.