MySQL 中的 Python 变量 [英] Python variables in MySQL

查看:39
本文介绍了MySQL 中的 Python 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Python 变量作为表名、列名和值,但此查询不起作用:

I would like to use Python variables as table name, column name and value but this query don't working:

def dodaj_do_bazy (wartosc, miejsce, tabela):

# Open database connection
db = MySQLdb.connect("localhost","slawomir","12345","testpy" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
#sql = "INSERT INTO ",tabela,"(",miejsce,") VALUES(",wartosc,")"
try:
   # Execute the SQL command
   cursor.execute('INSERT INTO %s (%s) VALUES (%s)' % tabela, miejsce, (wartosc))
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()


dodaj_do_bazy(wpis_email, "email", "mail")

推荐答案

在这里找到它:

这现在对我有用(python 2.7.6,MariaDB)

This is working for me now (python 2.7.6, MariaDB)

sql = """INSERT INTO %s (%s) VALUES (%s)""" % ( tabela, miejsce, wartosc )

并且您的插入值必须被引用wpis_email = """ '随便' """

And your insert value have to be quoted wpis_email = """ 'whatever' """

首先尝试不使用 try/except,因为这会吞噬任何错误消息

First try without the try/except, as this eats any error messages

这篇关于MySQL 中的 Python 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆