如何替换变量来查询SQL? [英] How to substitute variable to query SQL?

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

问题描述

我有以下查询行:

c.execute("""insert into apps (url)""")

我有变量 url,我尝试将其附加到查询插入中.

I have variable url that I try to append in query insert.

但是你得到了 Mysql 语法错误

But U get Mysql sintax error

表中有两个字段:id - autoincrementurl

There are two field in table: id - autoincrement and url

推荐答案

更好的问题应该是 如何替换字符串中的值?" 作为您传递给 c 的查询.execute()string 格式.更好的是,如何动态格式化字符串的内容?"

The better question should be "How to substitute value in string?" as the query you are passing to the c.execute() is of the string format. Even better, "How to dynamically format the content of the string?"

在python中,有很多方法可以做到:

In python, to do that there are many ways:

  1. 使用str.format()

# Way 1: Without key to format
>>> my_string = "This is my {}"
>>> my_string.format('stackoverflow.com')
'This is my stackoverflow.com'

# Way 2:  with using key
>>> my_string = "This is my {url}"
>>> my_string.format(url='stackoverflow.com')
'This is my stackoverflow.com'

  • 使用字符串格式器 %s 作为:

    # Way 3: without key to %s
    >>> my_string = "This is my %s"
    >>> my_string % 'stackoverflow.com'
    'This is my stackoverflow.com'
    
    # Way 4: with key to %s
    >>> my_string = "This is my %(url)s"
    >>> my_string % {'url': 'stackoverflow.com'}
    'This is my stackoverflow.com'
    

  • <小时>

    对于特定于SQL 查询,更好的方法是传递如下值:


    For specific to SQL query, the better way is to pass value like:

    cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
    

    为了防止可能的SQL注入攻击

    这篇关于如何替换变量来查询SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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