I am trying to insert the API query response in to the SQL server database. On a particular field I need to check if the value of the field on the Query response is true or false , if it is false I need to insert 'F' if its true I need to insert 'T' a field in DB
cursor = sqlconn.cursor()
for index,row in roomsDF.iterrows():
cursor.execute("INSERT INTO SurplusMouse.RM_Room(ROOMID, NAME, DESCRIPTION, SHIPPING_FREEZE, UPDATEDNAME)\
values(?,?,?,?,?)"
,row['id']
,row['name']
,row['description']
, if row['shippingFreeze'] == false:
'F'
else:
'T'
,row['shippingFreeze'].split(' ', 1)
)
I see two errors here one on the cursor.execute(" as "(" was not closed and another issue is Expected expression Pylance erroron the if . This is my first Python script and not sure if I am missing something any help is greatly appreciated
It seems to me you are mixing two different concepts. You need to divide and conquer.
Retrieve the data, and create a variable for each value.
id = row['id']
name = row['name']
shippingFreeze = 'T' if row['shippingFreeze'] else 'F'
Then, create the execute command. Make sure that the shippingFreeze attribute comes correctly formatted as boolean.
Regards
L.
Related
this is my first post on stack overflow... thanks in advance for any and all help
I am very new to programming and i created a function in Python to dynamically search an sqlite3 database rather than entering in tons of queries. i will show the code and try to explain what i intended to happen at all the stages. In short my cursor.fetchall() always evaluates to empty even when i am certain there is a value in the database that it should find.
def value_in_database_check(table_column_name: str, value_to_check: str):
db, cursor = get_connection() # here i get a database and cursor connection
for tuple_item in schema(): # here i get the schema of my database from another function
if tuple_item[0] == "table": # now I check if the tuple is a table
schema_table = tuple_item[4] # this just gives me the table info of the tuple
# this lets me know the index of the column I am looking for in the table
found_at = schema_table.find(table_column_name)
# if my column value was found I will enter this block of code
if not found_at == -1:
table_name = tuple_item[1]
to_find_sql = "SELECT * FROM {} WHERE ? LIKE ?".format(table_name)
# value_to_check correlates to table_column_name
# example "email", "this#email.com"
cursor.execute(to_find_sql, (table_column_name, value_to_check))
# this always evaluates to an empty list even if I am certain that the
# information is in the database
fetch_to_find = cursor.fetchall()
if len(fetch_to_find) > 0:
return True
else:
return False
I believe ? can only be used as placeholder for values, not for names of tables or - as you try to do - columns. A likely fix (haven't tested it though):
to_find_sql = "SELECT * FROM {} WHERE {} LIKE ?".format(table_name, table_column_name)
cursor.execute(to_find_sql, (value_to_check, ))
I am implementing a student database project which has multiple tables such as student,class,section etc
I wrote a delete_table function which takes parameters table name and value to delete a row from a specific table but there seems to be some sort of syntax error in my code :
def delete_tables(tab_name,attr,value):
c.execute("delete from table=:tab_name where attribute=:attr is value=:value ",{'tab_name':tab_name, 'attr': attr, 'value': value})
input :
delete_tables('section','sec_name','S1')
error text :
c.execute("delete from table=:tab_name where attribute=:attr is value=:value ",{'tab_name':tab_name, 'attr': attr, 'value': value})
sqlite3.OperationalError: near "table": syntax error
I've tried all mentioned answers and what y'all are suggesting is that it'll also be insecure even if it works out. So Do i Have to write functions to delete every table individually instead of going for one single function, and is there any other alternative to this problem where I need not keep on writing n functions for n number of tables?????
Thanks in Advance :))
The problem is that you can't use parametrized queries (that :tab_name) on things others than values (? not sure I am using the right term): table names, column names and SQL keywords are forbidden.
where age > :max_age is OK.
where :some_col > :max_age is not.
where age :comparison_operator :max_age is not OK.
Now, you can build your own query using string concatenation or f strings, but... 🧨 this is a massive, massive SQL injection risk. See Bobby Tables Not to mention that concatenating values into SQL query strings quickly runs into issues when you have to deal with characters, numbers or None. (None => NULL, characters need quotes, numbers dont).
You could possibly build a query using string substitutions that accept only known values for the table and column names and then drives the delete criteria value using a parametrized query on :value.
(While this seems restrictive, letting a random caller determine which tables to delete is just not safe in the least).
Something like:
delete_tables(tab_name,attr,value):
safe_tab_name = my_dict_of_known_table_names[tab_name]
safe_attr = my_dict_of_known_column_names[attr]
# you have to `=`, not `is` here👇
qry = f"delete from {safe_tab_name} where {safe_attr} = :value "
# not entirely sure about SQLite's bind/parametrized syntax.
# look it up if needed.
c.execute(qry, dict(value = value))
Assuming a user only enters value directly, that at least is protected from SQL injection.
You need to have a look at what will be the exact SQL command that will be executed in the python method.
For the method call delete_tables('section', 'sec_name', 'S1') the SQL command that will be generated will be
delete from table=section where attribute=sec_name is value=S1
This will be an invalid command in SQL. The correct command should be
delete from section where sec_name='S1'
So you need to change your python function accordingly. The changes that need to be done should be as follows:
def delete_tables(tab_name, attr, value):
c.execute("delete from :tab_name where :attr = ':value'",
{'tab_name': tab_name, 'attr': attr, 'value':value})
def delete_tables(tab_name, attr, value):
c.execute("delete from " + tab_name + "where " + attr + " = " + value)
I think something like that will work, the issue is that you are trying to modify an attribute but its name is always attribute, for that you would like to make it a parameter in order to properly handle it.
Hope it helped.
Edit:
Check this SQLite python
What the c.execute does is to 'execute' a SQL query, so, you can make something like c.execute("select * from clients") if you have a clients table.
execute makes a query and brings you the result set (if it is the case), so if you want to delete from your table using a normal SQL query you would type in the console delete from clients where client_id = 12 and that statement will delete the client with id equal to 12.
Now, if you are using SQLite in python, you will do
c.execute("delete from clients where client_id = 12")
but as you wish it to be for any table and any field (attribute) it turns in the table name, the field name and the value of that field being variables.
tableName = "clients"
field = "client_id"
value = "12" #must be string because you would have to cast it from int in the execute
"""
if value is a varchar you must write
value = "'12'" because the '' are needed.
"""
c.execute("delete from " + tableName + " where " + field + " = " + value)
and in the top of that, as you want it to be a function
def delete_tables(tableName, field, value):
c.execute("delete from " + tableName+ "where " + field + " = " + value)
Edit 2:
aaron's comment is true, it is not secure, the next step you would do is
def delete_tables(tab_name, attr, value):
#no ':value' (it limits the value to characters)
c.execute("delete from :tab_name where :attr = :value",
{'tab_name': tab_name, 'attr': attr, 'value':value})
It is from Vatsal's answer
I am using Python 2.7 and MySQLdb. I have made a database which has a table called test and in it two fields (id, firstname). The whole script is about counting and showing how many same firstnames do we have. The part of the script is like this right now but of course it doesn't work due to the 2nd line:
Value = int(input("Type your first name: "))
x.execute("UPDATE test SET id=(last id)+1 WHERE firstname=%s", (Value,))
What I am trying to do is type a Firstname from my keyboard and upload that to the database. If there is already that firstname in the table change his id which is a VARCHAR and make the new id = Last id + 1. For example if I type Doe and there is also Doe as a firstname in the database change Doe's row id number which is 1 by adding 1 and making it 2.
Sorry for the late answer.
I highly suggest to make the ID an INT with AUTO INCREMENT and PRIMARY KEY in order to prevent duplicates, but this would not allow you to change it freely as you want.
You need to check if there is a duplicate of the name you wrote inside the database, am i right?
If there is not, add a new row.
If there is, increment that name's id by one.
In order to check if that name is already in the database, you will need to do a SQL query, then check the results and compare the names you found with the one you wrote.
First, the query to get the names already in the database.
Then, check if the name already exists.
Then again, update or insert a new line into the database.
x.execute("""SELECT firstname FROM test""")
for row in x:
result = row[0]
if result == name:
nameExists = True
else:
nameExists = False
if !nameExists:
x.execute("""INSERT INTO test(firstname, id) VALUES (%s), (%s)""", name, id)
else:
x.execute("""SELECT id FROM test WHERE firstname = %s""", name)
for row in x:
actualId = row[0]
actualId = actualId + 1;
x.execute("""UPDATE test SET id = %s WHERE firstname = %s""", actualId, name)
The code above may change based on your variable names or preferences.
Do not take it as working, and copy-paste it directly into your code.
I hope the answer will be satysfing and complete. If not, let me know. It's the first time i answer to a question, and i may have not done it properly.
Thank you for your understanding.
For example, if I have following code:
#people( sin, name, height,weight,eyecolor, haircolor,addr,gender,birthday )
sin = input("sin ---->")
gender = input("gender ---->")
I need check whether 'sin' is an integer or say, a 'INT' in oracle data type.
And whether gender is f or m.
How can I do this? Is there any different way from:
while gender != 'f' or gender != 'm':
gender = input("gender ---->")
The two attributes above will be insert into my database by SQL statement
I am using cx_Oracle
Can you use isinstance()?
isinstance(sin, int) will eval to true or false.
isinstance(object_instance, object_type) might work for the other objects you want to evaluate as well.
Your checking of 'f' or 'm' is a bit different since you're comparing data rather than type. Not sure if you can get around that way of checking data.
Hope that helps.
Im trying to do a simple check if there is 3 specific value in a string. If there is, the statement should return nothing, instead of save.
Here is my code, but I think the syntax is wrong:
if not ('2239687' or '2238484' or '2239440') in user_id:
#The user is not admin, save the user
web_user.save()
To elaborate, I want it to test if user_id is "2239687" or "2238484" or "2239440" (and not, for example, "002239440"). If the user_id is one of those three values (and ONLY those three values), the statement should return false.
if not any(x in user_id for x in ('2239687', '2238484', '2239440')):
#The user is not admin, save the user
web_user.save()
This checks whether none of the three string is present within user_id.
One more option:
if not any(idx in user_id for idx in ('2239687' ,'2238484' , '2239440')):
# do something
Try like this
if user_id not in ('2239687' ,'2238484' , '2239440'):
Or
if not user_id in ('2239687' ,'2238484' , '2239440'):