我的目标是创建一个数据库,其中包含描述标准普尔 500 成分股信息的表格(和条目)。
1) 我已经使用 Homebrew 软件安装了 MySQL,创建了一个数据库和一个名为“securities_master”的表
2)我打开spyder并输入以下内容
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# insert_symbols.py
"""
Created on Fri Jan 13 17:42:53 2017
@author:
"""
from __future__ import print_function
import datetime
from math import ceil
import bs4
import MySQLdb as mdb
import requests
def obtain_parse_wiki_snp500():
"""
Download and parse the Wikipedia list of S&P500
constituents using requests and BeautifulSoup.
Returns a list of tuples for to add to MySQL.
"""
# Stores the current time, for the created_at record
now = datetime.datetime.utcnow()
# Use requests and BeautifulSoup to download the
# list of S&P500 companies and obtain the symbol table
response = requests.get(
"http://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
)
soup = bs4.BeautifulSoup(response.text)
# This selects the first table, using CSS Selector syntax
# and then ignores the header row ([1:])
symbolslist = soup.select('table')[0].select('tr')[1:]
# Obtain the symbol information for each
# row in the S&P500 constituent table
symbols = []
for i, symbol in enumerate(symbolslist):
tds = symbol.select('td')
symbols.append(
(
tds[0].select('a')[0].text, # Ticker
'stock',
tds[1].select('a')[0].text, # Name
tds[3].text, # Sector
'USD', now, now
)
)
return symbols
def insert_snp500_symbols(symbols):
"""
Insert the S&P500 symbols into the MySQL database.
"""
# Connect to the MySQL instance
db_host = 'localhost'
db_user = 'root'
db_pass = ''
db_name = 'securities_master'
con = mdb.connect(
host=db_host, user=db_user, passwd=db_pass, db=db_name
)
# Create the insert strings
column_str = """ticker, instrument, name, sector,
currency, created_date, last_updated_date
"""
insert_str = ("%s, " * 7)[:-2]
final_str = "INSERT INTO symbol (%s) VALUES (%s)" % \
(column_str, insert_str)
# Using the MySQL connection, carry out
# an INSERT INTO for every symbol
with con:
cur = con.cursor()
cur.executemany(final_str, symbols)
if __name__ == "__main__":
symbols = obtain_parse_wiki_snp500()
insert_snp500_symbols(symbols)
print("%s symbols were successfully added." % len(symbols))
3) 以上内容是从书中逐字复制的,应该填充“securities_master”中的“symbol”表,但是如您所见,它会返回错误...
in [2]: runfile('/Users/alexfawzi/untitled4.py', wdir='/Users/alexfawzi')
Traceback (most recent call last):
File "<ipython-input-2-ecff2c9aa5ce>", line 1, in <module>
runfile('/Users/alexfawzi/untitled4.py', wdir='/Users/alexfawzi')
File "/Users/alexfawzi/anaconda/lib/python2.7/site- packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/Users/alexfawzi/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/alexfawzi/untitled4.py", line 92, in <module>
insert_snp500_symbols(symbols)
File "/Users/alexfawzi/untitled4.py", line 87, in insert_snp500_symbols
cur.executemany(final_str, symbols)
File "/Users/alexfawzi/anaconda/lib/python2.7/site-packages/MySQLdb/cursors.py", line 253, in executemany
r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]]))
File "/Users/alexfawzi/anaconda/lib/python2.7/site-packages/MySQLdb/cursors.py", line 346, in _query
rowcount = self._do_query(q)
File "/Users/alexfawzi/anaconda/lib/python2.7/site-packages/MySQLdb/cursors.py", line 310, in _do_query
db.query(q)
ProgrammingError: (1146, "Table 'securities_master.symbol' doesn't exist")
编程错误!该死!我无法想象从菜鸟的错误中找出答案会很有趣,所以非常感谢任何愿意花时间提供帮助的人。
最佳答案
关键是 SHOW TABLES;
显示 '
和 '
引号(又名“ curl ”引号),而不是.. ……好吧……没什么。该查询的结果应该显示完全不带引号的表名,这意味着您不小心创建了带有“ curl ”引号的表。
例如:
您的选择是像这样更改代码:
final_str = "INSERT INTO `‘symbol’` (%s) VALUES (%s)"
或者重新创建不带引号的表格。
做第二个。
我猜您最初是从网站或文档中复制表名,这可以解释为什么它会有“弯”引号而不是“直”引号 ('
)。在大多数编程语言中,直引号表示字符串,但在编程中实际上并不使用弯引号 - 它们在文本中被文字处理器和 WYSIWYG 编辑器替换。
关于mysql - python /MySQL : Programming error 1146 - Table doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654723/