How Can I Add New Value On Column Database /PYTHON - python

import sqlite3
con = sqlite3.connect("Demo.db")
cursor = con.cursor()
query = "UPDATE Table set demoName = %s Where demoId = %s"
cursor.execute(query,("demoName",1)
con.commit()
This method is not work.
I want to keep the current values ​​in the column and add more values ​​to those values. I can do that with what code. Updating doesn't work here.

UPDATE sql command is to update existing rows. Use the INSERT sql command to create new rows.
import sqlite3
con = sqlite3.connect("Demo.db")
cursor = con.cursor()
query = "INSERT INTO Table (demoName, demoId) VALUES (%s, %s)"
cursor.execute(query,("demoName",1)
con.commit()
Python official sqlite3 documentation suggests the following links for learning sql:
https://www.w3schools.com/sql/ - Tutorial, reference and examples for learning SQL syntax.
https://www.sqlite.org - The SQLite web page; the documentation describes the syntax and the available data types for the supported SQL dialect.

Related

Can I use an input to add things to a POSTGRES TABLE? (Python)

I'm trying to transfer a user input from a python code to a table in postgresql
What I want to do is place an input() in this code and make it's value go to the comment (#) in the code.
conn = psycopg2.connect(
host="localhost",
database="Twitterzuil",
user="postgres",
password="")
cur = conn.cursor()
cur.execute("INSERT INTO Bericht2 (name) VALUES (#THIS IS WHERE I WANT THE INPUT TO GO)");
conn.commit()
I have no idea how, I'm really a beginner in all this so any help is appreciated
I believe what you are asking about is called string interpolation. Using f-style format, this might look like
new_name = "'bob'" # need single quotes for SQL strings
sql = f"INSERT INTO Bericht2 (name) VALUES ({new_name})" # => sql == "INSERT INTO Bericht2 (name) VALUES ('bob')"
cur.execute(sql)
Note the f at the start of the string, when you do this expressions inside {} pairs get replaced with their python values (tutorial). There are also string formatting approaches involving % substitution and the .format method on strings.
If you are doing anything beyond the basics you should look into using the SQLAlchemy package; here's the link to their insert api. Using SQLAlchemy will help reduce the risks that can come with manually constructing SQL queries.
Example from "Inserting Rows with SQLAlchemy"
from sqlalchemy import insert
stmt = insert(user_table).values(name='spongebob', fullname="Spongebob Squarepants")
with engine.connect() as conn:
result = conn.execute(stmt)
conn.commit()

Using SQL with IBM_DB connector in Python

Has anyone used the ibm_db package with IBM's Python for PASE to update Db2 files on IBM i (formerly AS/400)?
I want to use Python scripts (from QSH) to update the Db2 database. My purpose is to populate values at runtime and update the fields of Db2 files. It works with static (hardcoded) values, but not dynamic ones.
Here is what I am trying, but it is not working:
import ibm_db
c1 = ibm_db.connect('*LOCAL','userid','password')
sql = """INSERT INTO TEMPLIB.TEMPPF (TYPE, DRPARTY, CRPARTY,
AMOUNT,ACNUM, DESCRIPT)
VALUES('%s', '%s', '%s', '%s', '%s', '%s'),
%(self.type, self.debitparty, self.creditparty, self.amount,
self.craccountnumber, self.description) with NC
"""
stmt = ibm_db.exec_immediate(c1, sql )
self.type, self.debitparty, etc. are Python instance variables and have values.
TYPE, DRPARTY, CRPARTY, etc. are fields of TEMPPF.
Something simpler like populating the 'sql' variable as below works:
sql = "select * from TEMPLIB.TEMPPF"
So somewhere I am not making the INSERT format correctly. Does anyone know the format please? I tried a couple of formats available on the Internet, but they are not compatible with Python, or they are not good examples.
First, your concatenation of strings with the modulus operator is not correct as %(vars) needs to reside outside the string intended to be formatted.
Second, you should be using SQL parameterization (an industry standard in any database, not just DB2) and not string interpolation of data and query statement. You can do so using the ibm_db_dbi module to pass parameters in the cursor execute call:
import ibm_db
import ibm_db_dbi # ADD DBI LAYER
db = ibm_db.connect('*LOCAL','userid','password')
# ADD FOR PYTHON STANDARD DB-API PROPERTIES (I.E., CURSOR)
conn = ibm_db_dbi.Connection(db)
cur = conn.cursor()
# PREPARED STATEMENT (WITH PLACEHOLDERS)
sql = """INSERT INTO TEMPLIB.TEMPPF (TYPE, DRPARTY, CRPARTY,
AMOUNT, ACNUM, DESCRIPT)
VALUES(?, ?, ?, ?, ?, ?)
with NC
"""
# EXECUTE ACTION QUERY BINDING PARAMS
cur.execute(sql, (self.type, self.debitparty, self.creditparty, self.amount,
self.craccountnumber, self.description))
cur.close()
conn.close()

Python - Can I insert rows into one database using a cursor (from select) from another database?

I am trying to select data from our main database (postgres) and insert it into a temporary sqlite database for some comparision, analytics and reporting. Is there an easy way to do this in Python? I am trying to do something like this:
Get data from the main Postgres db:
import psycopg2
postgres_conn = psycopg2.connect(connection_string)
from_cursor = postgres_conn.cursor()
from_cursor.execute("SELECT email, firstname, lastname FROM schemaname.tablename")
Insert into SQLite table:
import sqlite3
sqlite_conn = sqlite3.connect(db_file)
to_cursor = sqlite_conn.cursor()
insert_query = "INSERT INTO sqlite_tablename (email, firstname, lastname) values %s"
to_cursor.some_insert_function(insert_query, from_cursor)
So the question is: is there a some_insert_function that would work for this scenario (either using pyodbc or using sqlite3)?
If yes, how to use it? Would the insert_query above work? or should it be modified?
Any other suggestions/approaches would also be appreciated in case a function like this doesn't exist in Python. Thanks in advance!
You should pass the result of your select query to execute_many.
insert_query = "INSERT INTO smallUsers values (?,?,?)"
to_cursor.executemany(insert_query, from_cursor.fetchall())
You should also use a parameterized query (? marks), as explained here: https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute
If you want to avoid loading the entire source database into memory, you can use the following code to process 100 rows at a time:
while True:
current_data = from_cursor.fetchmany(100)
if not current_data:
break
to_cursor.exectutemany(insert_query, current_data)
sqlite_conn.commit()
sqlite_conn.commit()
You can look at executemany from pyodbc or sqlite. If you can build a list of parameters from your select, you can pass the list to executemany.
Depending on the number of records you plan to insert, performance can be a problem as referenced in this open issue. https://github.com/mkleehammer/pyodbc/issues/120

How can I check if a database table exists or not with Python?

I would like to check if a database table exists or not, but I don't know how to do.
I wrote (for example with SQLite, although I use MySQL mainly),
import sqlite3
table_name = "some_table"
connection = sqlite3.connect(db)
cursor = connection.cursor()
table_check = "SELECT name FROM sqlite_master WHERE type='table' AND name={};".format(table_name)
if not cursor.execute(table_check).fetchone(): # if the table doesn't exist
# OR if cursor.execute(table_check).fetchone() == "":
create_table()
else:
update_table()
But, an Error occured and I cannot proceed.
sqlite3.OperationalError: no such column: some_table
I read several Q&A here, but I couldn't get those.
Any advice can help me.
Thank you.
Python 3.5.1
The answer is depending on what rdbms product (mysql, sqlite, ms sql, etc.) you use.
You are getting this particular error in your above query because you do not enclose the value of table_name variable in single quotes.
In mysql you can use information_schema.tables table to query if a table exists.

MySQLdb Python Trouble creating and using a Table

I'm trying to make a mysql table with python 2.7 using MySQLdb.
I've written a program to retrieve tweets based off of a search or "query" from twitter.
I want the tweets to be stored in a MySQL database for later retrieval by their query.
Things to know beforehand: the variable "tweets" is a list of strings. I want the table to have two parts, the query (what the person searched) and the tweets.
What is supposed to happen, is it should cycle through the list of tweets and insert them into the table. I keep getting Syntax errors and I'm not sure why.
Maybe there is a better way to do this than how I am currently trying to? Or maybe I'm just doing it wrong? All suggestions appreciated.
Thanks
#Does the MySQL stuff
db=MySQLdb.connect(host = 'localhost',user='root',passwd="swag",db="tweets")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS TWEETS")
sql = """CREATE TABLE TWEETS (
QUERY CHAR(40) NOT NULL,
TWEET BLOB,
)"""
cursor.execute(sql)
#Inserts tweets into MySQLdb
for i in range(0,len(tweets)):
sql = "INSERT INTO TWEETS(QUERY, \
TWEET) \
VALUES ('%s', '%s')" % \
(query, tweets[i])
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()

Categories