【问题标题】:inserting data into mysql database with python使用python将数据插入mysql数据库
【发布时间】:2018-02-07 23:53:44
【问题描述】:

我正在尝试将从 Yahoo Finance 下载的股票市场 csv 数据插入到名为“TEST”的 mysql 表中,该表位于 一个名为“股票”的数据库,但我从 python 得到一个错误代码:

InternalError: (1292, "不正确的日期值: 'Date for column 'date at 第 1 行")

我试图插入的数据有数百行看起来像这样:

1995-03-31,0.141150,0.141150,0.141150,0.141150,0.105375,10000

我尝试将此数据插入的表包含以下列:

date DATE NOT NULL PRIMARY KEY,
open DECIMAL(10,6),
high DECIMAL(10,6),
low DECIMAL(10,6),
close DECIMAL(10,6),
adj_close DECIMAL(10,6),
volume INT,

这是我用来将数据插入表中的python代码

with open('/home/matt/Desktop/python_projects/csv_files/CH8_SG.csv', 
'r') as f:
     reader = csv.reader(f)
     data = next(reader)
     query = 'insert into TEST values (%s,%s,%s,%s,%s, %s, %s)'
     query = query.format(','.split('%s' * len(data)))
     cursor = connection.cursor()
     cursor.execute(query, data)
     for data in reader:
        cursor.execute(query, data)
     cursor.commit()

当我运行如上图所示的代码时,出现以下错误

InternalError: (1292, "不正确的日期值: 'Date for column 'date at row 1")

我真的认为我很接近,但我不知道这个错误是怎么回事。 谁能帮帮我?

【问题讨论】:

  • 我原本以为您陷入了使用字符串格式化查询的陷阱,然后意识到我不明白 query = query.format(','.split('%s' * len(data))) 做了什么。它似乎对测试没有任何作用。然后您再次定义cursor = connection.cursor()。您也使用cursor.commit(),但我认为应该是connection.commit()
  • data = next(reader) 之后,执行print(data)。你得到了什么?此外,您的错误可能是由于空行造成的。从您的问题无法判断。
  • print(data) 在 data = next(reader) 之后没有返回任何内容。我又收到了同样的错误信息
  • 我将 cursor.commit 更改为 connection.commit(),但仍然收到相同的错误消息。
  • 好吧,查看给定行中的日期。

标签: python mysql insert stock-data


【解决方案1】:

在 Python 中编写插入日期时间的查询时,应在 MySQL 中使用转换操作。在你的情况下: query = '插入测试值 (%s,%s,%s,%s,%s, %s, %s)' => '插入测试值 (STR_TO_DATE(%s),%s,%s,%s,%s, %s, %s)' 并确保“日期”字段中没有重复。

【讨论】:

  • 我尝试将 query = 行更改为以下各项: query = 'insert into TEST values (STR_TO_DATE(%s),%s,%s,%s,%s, %s, %s)' 然后我尝试: query = '插入 TEST 值 ((STR_TO_DATE(%s)),%s,%s,%s,%s, %s, %s)' 但仍然没有骰子。有任何想法吗?我对 python 太陌生了,所以我对自己没有太大帮助。我不断收到此错误消息“InternalError: (1582, "Incorrect parameter count in call to native function 'STR_TO_DATE'")”
  • 试试这个:“插入 TEST 值 (STR_TO_DATE(%s, '%Y-%m-%d'),%s,%s,%s,%s, %s, %s)" 它应该在 "STR_TO_DATE" 函数中指定日期字符串的格式。
  • reader = csv.reader(f) data = next(reader) query = "插入测试值((datetime.datetime.striptime((%s),%s,%s,%s ,%s, %s, %s)" query = query.format(','.split('%s' * len(data))) cursor = connection.cursor() cursor.execute(query, data) for阅读器中的数据: cursor.execute(query, data) cursor.commit()
  • 感谢您为我提供的所有帮助。 Python 给了我关于 Y 字符的问题,所以我弄乱了代码,并在上面评论中的代码上向前迈出了一大步。但现在我收到此错误消息:“(1064,“您的 SQL 语法有错误;...检查在 '(('Date'),'Open','High', 'Low','Close', 'Adj Close', 'Volume')' 在第 1 行")
  • 对我来说,很明显错误是python格式化日期和要插入mysql表的数字的方式。 Python 可能会在日期中留下引号或在数字中添加引号,并且会弄乱插入语句。我认为此时我必须弄清楚如何以 mysql 想要的方式格式化输出
猜你喜欢
  • 2023-03-08
  • 2020-04-01
  • 2014-04-17
  • 2015-08-23
  • 2014-07-09
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多