Python MySQLdb cursor.execute() insert with varying number of values

2024/10/15 13:23:36

Similar questions have been asked, but all of them - for example This One deals only with specified number of values.

for example, I tried to do this the following way:

def insert_values(table, columns, values, database):"""columns - a string representing tuple with corresponding columnsvalues - a tuple containing values"""query=database.cursor()query.execute("INSERT INTO `{}` {} VALUES{}".format(table,columns,str(values))) 

But that's no good - although the insert initially seemed fine (accepted and commited to database), soon the data types errors began, which came from converting all data types to string. For example:

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

My initial way also involved pre-converting datetime objects, which is probably not what the creators of MySQLdb had in mind.

The way I saw in other examples for MySQLdb involves string interpolation, but that means defined number of variables as '%s', and it gives no flexibility to the code.

How could I define a method, which could take an arbitrary, previously undefined number of values that would be compatibile with MySQLdb? Is it possible? Or am I missing something about string interpolation?

[edit] example usage of a method I had in mind:

two databases: source_db, destination_db

row = source_db.cursor.execute('SELECT x from Y where z='1')

(returns tuple)

insert_values('table_name','(column_name_1,column_name_2)',row, destination_db)
Answer

You should use string interpolation to produce placeholders for the content, then allow the DB-API to populate them. For example:

placeholders = ','.join('%s' for col in columns)
query_string = "INSERT INTO `{}` {} VALUES ({})".format(table, columns, placeholders)
query.execute(query_string, values)
https://en.xdnf.cn/q/117831.html

Related Q&A

Searching in a .txt file and Comparing the two values of a string in python?

"cadence_regulatable_result": "completeRecognition","appserver_results": {"status": "success","final_response": 0,"payload": {"…

How to perform an HTTP/XML authentication with requests

I am trying to authenticate to Docushare with Python 3.4 using requests 2.7. I am relatively new to Python and to the requests module but Ive done a lot of reading and am not able to make any more prog…

webPy Sessions - Concurrent users use same session and session timeout

I have a webPy app using sessions for user authentication. Sessions are initiated like so:web.config.debug=Falsestore = web.session.DiskStore(/path_to_app/sessions) if web.config.get(_session) is None:…

get text content from p tag

I am trying to get description text content of each block on this page https://twitter.com/search?q=data%20mining&src=typd&vertical=default&f=users. html for p tag looks like<p class=&q…

Python - making a function that would add - between letters

Im trying to make a function, f(x), that would add a "-" between each letter:For example:f("James")should output as:J-a-m-e-s-I would love it if you could use simple python function…

python script keeps converting dates to utc

I have the following:import psycopg2 from openpyxl import Workbook wb = Workbook() wb.active =0 ws = wb.active ws.title = "Repair" ws.sheet_properties.tabColor = "CCFFCC"print(wb.sh…

sklearn tsne with sparse matrix

Im trying to display tsne on a very sparse matrix with precomputed distances values but Im having trouble with it.It boils down to this:row = np.array([0, 2, 2, 0, 1, 2]) col = np.array([0, 0, 1, 2, 2,…

Removing a sublist from a list

I have a list e.g. l1 = [1,2,3,4] and another list: l2 = [1,2,3,4,5,6,7,1,2,3,4]. I would like to check if l1 is a subset in l2 and if it is, then I want to delete these elements from l2 such that l2 …

Python double FOR loops without threading

Basically, I want to make a grid with school subjects and all the test results I got from it, and I want to display about 10 results for every subject.Like this:... ------------------------------------…

Challenging way of counting entries of a file dynamically

I am facing a strange question, which despite of trying many times, i am not able to find the logic and proper code to the problem. I have a file in the format below: aa:bb:cc dd:ee:ff 100 ---------…