代码之家  ›  专栏  ›  技术社区  ›  Jason Webb

如何在python中使用SQL参数?

  •  13
  • Jason Webb  · 技术社区  · 14 年前

    pymssql 1.9.908 .

    using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection))
    {
        com.Parameters.AddWithValue("@CustomerID", CustomerID);
        //Do something with the command
    }
    

    我试图找出python的等价物,尤其是pymssql。我意识到我可以只做字符串格式化,但是这似乎不像参数那样正确地处理转义(我可能在这方面错了)。

    如何在python中执行此操作?

    1 回复  |  直到 14 年前
        1
  •  23
  •   Alex Martelli    14 年前

    db :

    cursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id])
    

    然后使用 fetch... 产生结果的方法 cursor 对象。

    %s 部分:这不是字符串格式,而是参数替换(不同的DB API模块使用不同的语法进行参数替换——pymssql恰好使用 %s码 !-).