使用与python和mysql连接器一样编写查询

时间:2017-05-04 10:30:18

标签: python mysql python-3.x wildcard

如何使用与mysql连接器和python类似的方式编写查询。我试图避免sql注入,并且使用ORM不是一种选择。

public static void main(String[] args) throws Exception {

    try {

        Docx4jProperties.getProperties().setProperty("docx4j.Log4j.Configurator.disabled", "true");
        Log4jConfigurator.configure();
        org.docx4j.convert.out.pdf.viaXSLFO.Conversion.log.setLevel(Level.OFF);

        System.out.println("Getting input Docx File");
        InputStream is = new FileInputStream(new File(
                "C:/Users/nithins/Documents/plugin docx to pdf/other documents/Contains Complex Fonts Verified.docx"));
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
        wordMLPackage.setFontMapper(new IdentityPlusMapper());

        System.out.println("Setting File Encoding");
        System.setProperty("file.encoding", "Identity-H");
        System.out.println("Generating PDF file");

        org.docx4j.convert.out.pdf.PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
                wordMLPackage);
        File outFile = new File(
                "C:/Users/nithins/Documents/plugin docx to pdf/other documents/Contains Complex Fonts Verified.pdf");
        OutputStream os = new FileOutputStream(outFile);
        c.output(os, new PdfSettings());
        os.close();

        System.out.println("Output pdf file generated");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static String changeExtensionToPdf(String path) {
    int markerIndex = path.lastIndexOf(".docx");
    String pdfFile = path.substring(0, markerIndex) + ".pdf";
    return pdfFile;
}

无论我在查询执行时发送什么,我都会得到相同的结果。我什么都没得到。

当我使用以下查询时,我收到错误。

       param = 'bob'
       select_query = mysql_conn.query_db("select * from table_one where col_name like '%?%' order by id asc limit 5", param)

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便在ID为asc limit 5'%s附近使用。在第1行

3 个答案:

答案 0 :(得分:3)

您需要在转义之前将%通配符添加到param,例如:

select_query = mysql_conn.query_db(
    "select * from table_one where col_name like %s order by id asc limit 5",
     ("%{}%".format(param),)
)

此外,参数应作为上面的元组传递,或者在使用命名参数时作为dict传递:

select_query = mysql_conn.query_db(
    "select * from table_one where col_name like %(p)s order by id asc limit 5",
     {"p": "%{}%".format(param)}
)

答案 1 :(得分:1)

  

请注意,传递给查询字符串的任何文字百分号   必须转义execute(),即%%

http://mysql-python.sourceforge.net/MySQLdb.html

这与旧式python字符串格式化,c printf等等几乎相同

答案 2 :(得分:0)

您需要在转义之前将%通配符添加到要传递的参数中,例如:

select_query = mysql_conn.query_db( “从table_one中选择*,其中col_name类似于%s,按ID升序限制ID 5”, (“%{}%”。format(param),) )

丢了我一个错误

TypeError:需要一个类似字节的对象,而不是'tuple'

所以对我有用的是将引号明确编码为选择引号,如下所示:

  "select * from table_one where col_name like \"%"+param+"%\" order by id asc limit 5"