im trying to insert values into a column that a user has asked to be changed which is called surnamereq and the user change which is called name1. money_spent is the name of the table and first_name is the column that the user is changing the value of.
This is how it should be written in SQL(i think):
INSERT INTO money_spent(first_name)
WHERE last_name = surnamereq
VALUES(name1)
This is what ive got in python:
cursor.execute("INSERT INTO money_spent(first_name) WHERE last_name = ?, surnamereq VALUES(name1)")
Thanks
The documentation for the .execute method shows that the form of the method call is
execute(sql, *parameters)
and states that
The optional parameters may be passed as a sequence, as specified by the DB API, or as individual values.
So, you could either do
surnamereq = 'Thompson'
fname = 'Gord'
#
sql = "UPDATE money_spent SET first_name = ? WHERE last_name = ?"
params = (fname, surnamereq)
cursor.execute(sql, params)
or
surnamereq = 'Thompson'
fname = 'Gord'
#
sql = "UPDATE money_spent SET first_name = ? WHERE last_name = ?"
cursor.execute(sql, fname, surnamereq)
Note that the second approach is a pyodbc-specific extension to the DB API.
Related
I think I have made some mistake in creating new table in SQL by mentioning its column also. Could anyone please review the code let me know your thoughts on this
db = conn.connect(
host ="Localhost",
user ="root",
passwd ="admin",
database = "EMPLOYEE_DETAILS_00"
)
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Details ( User_ID VARCHAR(255), Name VARCHAR(255), Age VARCHAR(255), Occupation VARCHAR(255), Department VARCHAR(255), Salary VARCHAR(255), Address VARCHAR(255) ) ")
I need to write a nested Python dictionary into a SQL table. I'm trying to do it by using a for loop but I'm getting the following error:
Error : Couldn't process parameters
Can anyone provide me with any suggestions on this?
This is the code I'm trying to run:
user_details = {}
create_user_ID = input(" Enter the user ID : ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
for v in user_details.values():
cols = v.keys()
vals = v.values()
sql = "INSERT INTO Details ({}) VALUES ({})".format(
', '.join(cols),
', '.join(['%s'] * len(cols)));
cursor.execute(sql, vals)
I would say your problem is at the last line, when you try to do cursor.execute(sql,(val,)).
In Python 3 dict.keys() and dict.values() doesn't return lists, but some dictionary view objects wrapping the data, so what you're getting from (val,) is a single value tuple with one dict_values object.
Try using just val as #niteshbisht suggested or list(val) or tuple(val) if that still doesn't work.
Please see also Python nested dictionary with SQL insert, as it looks like you're trying to address the same problem.
DON'T use the most obvious one (%s with %) in real code, it's open to attacks.
sql = ("INSERT INTO Details ? Values ?" ,(col, placeholders))
cursor.execute(sql,val)
My Python code uses pyodbc to connect to a database and then asks the user for input which I would like to format the 'where' clause in an SQL statement but the where clause requires single quotation marks on my user input to function.
Every time I have tried to format the input to include single quotation mark it doesn't seem work and returns back no rows.
Here is what I am trying to achieve
"select FirstName, LastName from person.person where FirstName = 'Kim'"
where 'Kim' should be the user input.
here in my code section.
user_first_name = print(input("Enter the first name you are looking
for: "))
cursor.execute("select FirstName, LastName from person.person where
FirstName = ?", (user_first_name))
how do I format the input (user_first_name) so that the parameter has the single quotes in the query field.
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-3NLISNE\SQLNEW;DATABASE=TestDB;UID=python;PWD=password')
cursor = cnxn.cursor()
user_first_name = print(input("Enter the first name you are looking for:"))
query = "select FirstName, LastName from person.person where FirstName = ?"
result = cursor.execute(query, (user_first_name,))
rows = result.fetchall()
print (rows)
Using Python's mysql.connector, how can I select all records that match a tuple?
For example:
ids = (b'6TRsHMzWSrq0zeembo0Vbg',
b'7Qoq53lKTk-RZOi830t3MA',
b'7ZGO9S3DTcGHjwrfpV0E0A')
And then the query would do something like:
query = SELECT first_name
FROM users
WHERE id = (ids)
Returning records for all users whose ID appears in the tuple
Try doing this
query = "SELECT first_name FROM users WHERE id IN " + str(list(ids))
cursor.execute(query)
On second thoughts, the following should also work
query = "SELECT first_name FROM users WHERE id IN " + str(ids)
EDIT
OP mentions in comments that the ids are binary data returned from a previous query. In which case, taking hint from this answer and using BINARY operator, the following query should work
query = "SELECT first_name FROM users WHERE BINARY id IN " + str(ids) ;
New to Python and Databases
I have a database table set up with a column of usernames. I want the user to be able to search through the table via a raw_input and only return the values which are associated with that user name.
E.g. user searches for Bill and it only displays Bill's records ordered by a specified column
This is what I have so far but its obviously VERY wrong, hope someone can help:
def find_me(db, column_name):
db = sqlite3.connect(db)
cursor = db.cursor()
name = raw_input("Please enter your username: ")
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
cursor.execute("SELECT * FROM username ORDER BY "+column_name+" ASC")
name = cursor.fetchone()
next = cursor.fetchone()
Thank you in advance
You want to make the query similar to the following:
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
This uses query parameters, so it's correctly escaped for the data provided. Then just adapt this to SELECT * and whatever else you want from the result.
Try working with this:
name = raw_input("Please enter your username: ")
query = "SELECT * FROM username WHERE name=? ORDER BY {0}".format(column_name)
cursor.execute(query, (name,))
for row in cursor:
print row
I am using SQLAlchemy without the ORM, i.e. using hand-crafted SQL statements to directly interact with the backend database. I am using PG as my backend database (psycopg2 as DB driver) in this instance - I don't know if that affects the answer.
I have statements like this,for brevity, assume that conn is a valid connection to the database:
conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)")
Assume also that the user table consists of the columns (id [SERIAL PRIMARY KEY], name, country_id)
How may I obtain the id of the new user, ideally, without hitting the database again?
You might be able to use the RETURNING clause of the INSERT statement like this:
result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)
RETURNING *")
If you only want the resulting id:
result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)
RETURNING id")
[new_id] = result.fetchone()
User lastrowid
result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)")
result.lastrowid
Current SQLAlchemy documentation suggests
result.inserted_primary_key should work!
Python + SQLAlchemy
after commit, you get the primary_key column id (autoincremeted) updated in your object.
db.session.add(new_usr)
db.session.commit() #will insert the new_usr data into database AND retrieve id
idd = new_usr.usrID # usrID is the autoincremented primary_key column.
return jsonify(idd),201 #usrID = 12, correct id from table User in Database.
this question has been asked many times on stackoverflow and no answer I have seen is comprehensive. Googling 'sqlalchemy insert get id of new row' brings up a lot of them.
There are three levels to SQLAlchemy.
Top: the ORM.
Middle: Database abstraction (DBA) with Table classes etc.
Bottom: SQL using the text function.
To an OO programmer the ORM level looks natural, but to a database programmer it looks ugly and the ORM gets in the way. The DBA layer is an OK compromise. The SQL layer looks natural to database programmers and would look alien to an OO-only programmer.
Each level has it own syntax, similar but different enough to be frustrating. On top of this there is almost too much documentation online, very hard to find the answer.
I will describe how to get the inserted id AT THE SQL LAYER for the RDBMS I use.
Table: User(user_id integer primary autoincrement key, user_name string)
conn: Is a Connection obtained within SQLAlchemy to the DBMS you are using.
SQLite
======
insstmt = text(
'''INSERT INTO user (user_name)
VALUES (:usernm) ''' )
# Execute within a transaction (optional)
txn = conn.begin()
result = conn.execute(insstmt, usernm='Jane Doe')
# The id!
recid = result.lastrowid
txn.commit()
MS SQL Server
=============
insstmt = text(
'''INSERT INTO user (user_name)
OUTPUT inserted.record_id
VALUES (:usernm) ''' )
txn = conn.begin()
result = conn.execute(insstmt, usernm='Jane Doe')
# The id!
recid = result.fetchone()[0]
txn.commit()
MariaDB/MySQL
=============
insstmt = text(
'''INSERT INTO user (user_name)
VALUES (:usernm) ''' )
txn = conn.begin()
result = conn.execute(insstmt, usernm='Jane Doe')
# The id!
recid = conn.execute(text('SELECT LAST_INSERT_ID()')).fetchone()[0]
txn.commit()
Postgres
========
insstmt = text(
'''INSERT INTO user (user_name)
VALUES (:usernm)
RETURNING user_id ''' )
txn = conn.begin()
result = conn.execute(insstmt, usernm='Jane Doe')
# The id!
recid = result.fetchone()[0]
txn.commit()
result.inserted_primary_key
Worked for me. The only thing to note is that this returns a list that contains that last_insert_id.
Make sure you use fetchrow/fetch to receive the returning object
insert_stmt = user.insert().values(name="homer", country_id="123").returning(user.c.id)
row_id = await conn.fetchrow(insert_stmt)
For Postgress inserts from python code is simple to use "RETURNING" keyword with the "col_id" (name of the column which you want to get the last inserted row id) in insert statement at end
syntax -
from sqlalchemy import create_engine
conn_string = "postgresql://USERNAME:PSWD#HOSTNAME/DATABASE_NAME"
db = create_engine(conn_string)
conn = db.connect()
INSERT INTO emp_table (col_id, Name ,Age)
VALUES(3,'xyz',30) RETURNING col_id;
or
(if col_id column is auto increment)
insert_sql = (INSERT INTO emp_table (Name ,Age)
VALUES('xyz',30) RETURNING col_id;)
result = conn.execute(insert_sql)
[last_row_id] = result.fetchone()
print(last_row_id)
#output = 3
ex -