代码之家  ›  专栏  ›  技术社区  ›  Shams Nahid

如何将变量放入'pyodbc'查询中?

  •  0
  • Shams Nahid  · 技术社区  · 7 年前

    我在用 pyodbc 在Microsoft SQL Server中保存数据。

    I 3个字符串变量, user_first_name , user_last_name profile_photo_path

    user_first_name = 'Shams'
    user_last_name = 'Nahid'
    file_name = 'my_profile_photo_path'
    

    现在当我尝试使用

    cursor.execute(f'''
                        INSERT INTO pyUser.dbo.user_information (first_name, last_name, profile_photo_path)
                        VALUES
                        ({user_first_name}, {user_last_name}, {file_name})
    
                        ''')
    

    我得到以下错误

    列名“Shams”无效。

    列名“Nahid”无效。

    无法绑定多部分标识符“directory.PNG”。

    但是如果我把硬编码的字符串

    cursor.execute('''
                        INSERT INTO pyUser.dbo.user_information (first_name, last_name, profile_photo_path)
                        VALUES
                        ('my_user_first_name', 'my_user_last_name', 'my_file_name')
    
                        ''')
    

    然后查询显示没有错误。

    我检查了变量类型, 用户名 , 用户名 file_name 都是 <class 'str'>

    如何将变量放入查询中?

    4 回复  |  直到 7 年前
        1
  •  1
  •   Gord Thompson    7 年前

    使用字符串格式将列值插入SQL语句是一种危险的做法,因为它会将代码暴露给 SQL注入 漏洞。例如,中的代码 your answer 会为你工作

    user_last_name = "Nahid"
    

    但它将以失败告终

    user_last_name = "O'Connor"
    

    SQL注入还可能带来严重的安全隐患。在网上搜索“小Bobby Tables”可以看到一个例子。

    相反,你应该使用 参数化查询 就像这样:

    user_first_name = 'Shams'
    user_last_name = 'Nahid'
    file_name = 'my_profile_photo_path'
    
    sql = '''\
    INSERT INTO pyUser.dbo.user_information (first_name, last_name, profile_photo_path)
    VALUES (?, ?, ?)
    '''
    params = (user_first_name, user_last_name, file_name, )
    cursor.execute(sql, params)
    
        2
  •  1
  •   Y.sir    7 年前

    我再试一次,比如说工作

    import pymysql
    
    def test():
        db = pymysql.connect('localhost', 'root', '****', 'python')
        cur = db.cursor()
        id_ = "123456"
        query = ''.join(["select *", " from customer where id = ", id_])
        cur.execute(query)
        result = cur.fetchone()
        print("result: ", result)
    if __name__ == '__main__':
        test()
    
        3
  •  0
  •   Shams Nahid    7 年前

    通过在变量的两边加上引号来解决。

    cursor.execute(f'''
                        INSERT INTO pyUser.dbo.user_information (first_name, last_name, profile_photo_path)
                        VALUES
                        ('{user_first_name}', '{user_last_name}', '{file_name}')
    
                        ''')
    
        4
  •  0
  •   Denis Sablukov    7 年前

    或者你可以试试这个

    cursor.execute('''
                        INSERT INTO pyUser.dbo.user_information (first_name, last_name, profile_photo_path)
                        VALUES
                        ("Shams", "Nahid", "my_profile_photo_path")
    
                        ''')