简体   繁体   中英

Python - taking a variable and inserting into a mysqlDB

This is probably simpler than I've made it.

basically I'm writing my second python script here. I want to open a mysql connection, process a for loop, and then insert the x int into a database.

I have everything working, expect, I'm unsure of how to insert the xstring instead of literal xstring. In C# it would be '" + xstring +"' but i'm not sure how to do this in Python.

Thanks!

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
con = mdb.connect('localhost', 'root', 'root', 'PythonTest');
with con:
        cur = con.cursor()
        for x in range(0, 3):
                xstring = str(x)

                    cur.execute("INSERT INTO Testing(KeyColumn,KeyValue) VALUES('Jack London','"xstring"')

except _mysql.Error, e:

print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

finally:

if con:
    con.close()

Python's DB API specification specifies it like this:

cur.execute("INSERT INTO Testing(KeyColumn,KeyValue) VALUES('Jack London', %s), (x,))

Warning: Never, ever use raw string formatting on DB queries, that would allow little B obby Tables to inject nasty things into your DB. Instead use library methods for parameterizing SQL queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM