【问题标题】:pyodbc - inserting selected rows (access mdb)pyodbc - 插入选定的行(访问 mdb)
【发布时间】:2023-03-07 16:20:01
【问题描述】:

从 Access .mdb 表中插入选定的记录/行时,我在此代码块的第 23 行找到了“Syntax error in INSERT INTO statement. (-3502)”。

我想要发生的是

  1. 创建表'65001'
  2. 从表“LMR_Combined”中选择前 65000 行
  3. 将这些选定的行插入到新创建的“65001”表中。

这个 INSERT INTO 语句中的什么语法错误阻止了成功执行?

import pyodbc
DBFile = r'C:\Python27\FCC_Processing\LMR Combined.mdb'
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBFile)

cursor = conn.cursor()


# Creates a table "65001" in the MDB that matches the schema of table "LMR_Combined"
string = "CREATE TABLE 65001(OBJECTID integer, Unique_ID varchar(255), LICENSEE_NAME varchar(255))"

cursor.execute(string)

# Selects 65000 records from table "LMR_Combined"
cursor.execute('select OBJECTID, Unique_ID, LICENSEE_NAME from LMR_Combined where OBJECTID > 0 and OBJECTID < 65001')

row = cursor.fetchone()

# For debugging, print a line
if row:
    print row

# Inserts the 65000 rows into the new table "65001"
cursor.execute('insert OBJECTID, Unique_ID, LICENSEE_NAME into 65001')

conn.commit()

提前致谢

【问题讨论】:

    标签: sql ms-access pyodbc


    【解决方案1】:

    考虑使用SELECT...INTO Statement 创建和填充您的65001 表是否足够:

    SELECT OBJECTID, Unique_ID, LICENSEE_NAME
    INTO [65001]
    FROM LMR_Combined
    WHERE OBJECTID > 0 AND OBJECTID < 65001;
    

    如果您需要不同于SELECT...INTO 提供的数据类型,请执行您的CREATE TABLE,然后执行此INSERT

    INSERT INTO [65001] (OBJECTID, Unique_ID, LICENSEE_NAME)
    SELECT OBJECTID, Unique_ID, LICENSEE_NAME
    FROM LMR_Combined
    WHERE OBJECTID > 0 AND OBJECTID < 65001;
    

    【讨论】:

    • 感谢 HansUp - SELECT INTO 语句非常完美。对于搜索者:我实际使用的pyodbc特定代码是cursor.execute('SELECT OBJECTID, Unique_ID, LICENSEE_NAME into [65001] from LMR_Combined where OBJECTID &gt; 0 AND OBJECTID &lt;65001')
    【解决方案2】:

    你的语法错误。

    在表中插入数据的正确方法是:

    insert into table1 (field1, field2, ...)
    select ...
    

    或者:

    insert into table1(field1, field2, ...)
    values (value1, value2, ...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2023-03-13
      • 2019-09-02
      相关资源
      最近更新 更多