将Pandas数据插入Oracle表时遇"expecting Number"错误求助
问题排查:Pandas插入Oracle时出现"期望数字"错误
问题背景
收到若干Excel格式数据,通过Pandas处理后插入Oracle数据表,运行代码时触发expecting Number(期望数字)错误,无法完成插入。已配置数据库账号密码、TNS文件中的HOST/PORT/服务名,且已连接VPN。
运行代码
import cx_Oracle import datetime as dt import pandas as pd # connection string in the format # <username>/<password>@<dbHostAddress>:<dbPort>/<dbServiceName> connStr = '<username>/<password>@<dbHostAddress>:<dbPort>/<dbServiceName>' # initialize the connection object conn = None try: # create a connection object conn = cx_Oracle.connect(connStr) # get a cursor object from the connection cur = conn.cursor() # read dataframe from excel df = pd.read_excel('C:...', sheet_name='...', header=11) # reorder the columns as per the requirement df.columns = ["COL_1","COL_2","COL_3","COL_4"] # prepare data insertion rows from dataframe dataInsertionTuples = [tuple(x) for x in df.values] # create sql for data insertion sqlTxt = 'INSERT INTO MYTABLE\\ (COL_1, COL_2, COL_3, COL_4)\\ VALUES (:1, :2, :3, :4)' # execute the sql to perform data extraction cur.executemany(sqlTxt, dataInsertionTuples) rowCount = cur.rowcount print("number of inserted rows =", rowCount) # commit the changes conn.commit() except Exception as err: print('Error while inserting rows into db') print(err) finally: if(conn): # close the cursor object to avoid memory leaks cur.close() # close the connection object also conn.close() print("number of inserted rows =", rowCount)
排查与解决步骤
1. 数据类型不匹配(最可能原因)
Oracle目标表中某列定义为数字类型,但Excel对应列存在非数字内容(空值、字符串、特殊符号等):
- 先确认
MYTABLE中COL_1至COL_4的字段类型,对比Excel对应列的实际内容。 - 用Pandas检查数据类型:
若某数字列显示为print(df.dtypes)object类型,说明存在非数字值。 - 清理异常值,示例:假设
COL_2为数字列,将非数字值转为0:df['COL_2'] = pd.to_numeric(df['COL_2'], errors='coerce').fillna(0)
2. 修复SQL语句换行问题
原代码中SQL用\\换行可能导致语法异常,改用三引号定义SQL:
sqlTxt = '''INSERT INTO MYTABLE (COL_1, COL_2, COL_3, COL_4) VALUES (:1, :2, :3, :4)'''
3. 检查空值兼容性
Oracle数字列无法直接接受Python的None,需转为兼容格式:
- 可在Pandas中提前将空值替换为0或符合业务规则的默认值。
- 或使用
cx_Oracle提供的空值常量,例如cx_Oracle.NULL。
4. 验证插入数据内容
打印部分待插入数据,确认是否存在不符合要求的元素:
print(dataInsertionTuples[:5]) # 查看前5条数据元组
内容的提问来源于stack exchange,提问作者Lefteris Kyprianou
相关产品推荐
相关产品推荐

