【问题标题】:sqlite python 3 insert OperationalError syntaxsqlite python 3插入OperationalError语法
【发布时间】:2018-12-12 02:50:19
【问题描述】:

所以我有一个函数可以读取一个 txt,对其进行解析,然后将其加载到一个 sql 表中。

 def main():
    connection = sqlite3.connect("myTable.db")
    crsr = connection.cursor()
    lines = open("LLA03132A.txt", "r").readlines()
    input = Thpt(lines)
    sql = """CREATE table if not exists my_table (
    date STRING,
    site STRING,
    sector STRING,
    avg_thpt FLOAT
    );"""
    crsr.execute(sql)
    for x in input:
        time = x[0]
        site = x[1][1:8]
        sector = x[1]
        avg_thpt = x[2]
        sql = """INSERT INTO my_table VALUES ( %s , %s , %s , %f );"""%(time, site, sector, avg_thpt)
        print(sql)
        crsr.execute(sql)
    connection.commit()
    connection.close()

但是,当我调用它时,我得到了这个错误。我究竟做错了什么?我是否错误地命名了我的类别或我的价值观?某处有隐藏角色吗?我也在使用 datetime 包,仅供参考

  Traceback (most recent call last):
INSERT INTO my_table VALUES ( 2018-07-03 10:14:18.060416 , LA03132 , LLA03132A11 , 2637.806265 );
  File "C:/Users/myname/PycharmProjects/Parser/parser2.py", line 60, in <module>
    main()
  File "C:/Users/myname/PycharmProjects/Parser/parser2.py", line 55, in main
    crsr.execute(sql)
sqlite3.OperationalError: near "10": syntax error

【问题讨论】:

    标签: python sql sqlite syntax operationalerror


    【解决方案1】:

    当您应该使用参数传递时,您正在使用字符串插值,这既慢又不安全。

    sqlite3.paramstyle 也是 'qmark',因此您应该使用 ? 作为参数的占位符:

    params = (x[0], x[1][1:8], x[1], x[2])
    sql = """INSERT INTO my_table VALUES (?, ?, ?, ?);"""
    print(sql)
    crsr.execute(sql, params)
    

    请注意,sql 和参数是分开传递给驱动程序的,因此数据库的工作是进行参数插值。这使您从引用地狱中解放出来,并通过不允许 sql 注入攻击使您的代码更安全。它也更快。

    【讨论】:

      【解决方案2】:

      问题是您试图将STRING 值插入到数据库中而没有适当的引用。如果您查看打印的 INSERT 语句,它会打印:

      INSERT INTO my_table VALUES ( 2018-07-03 10:14:18.060416 , LA03132 , LLA03132A11 , 2637.806265 );
      

      你想要的是它打印出来:

      INSERT INTO my_table VALUES ( '2018-07-03 10:14:18.060416' , 'LA03132' , 'LLA03132A11' , 2637.806265 );
      

      所以你需要更改这行代码:

      sql = """INSERT INTO my_table VALUES ( %s , %s , %s , %f );"""%(time, site, sector, avg_thpt)
      

      到这里:

      sql = """INSERT INTO my_table VALUES ( '%s' , '%s' , '%s' , %f );"""%(time, site, sector, avg_thpt)
      

      【讨论】:

        猜你喜欢
        • 2023-01-10
        • 2022-12-20
        • 2021-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多