2017-01-14 33 views
1

私の目標は、S & P 500の成分に関する情報を記述するテーブル(およびエントリ)を含むデータベースを作成することです。Python/MySQL:プログラミングエラー1146 - テーブルが存在しません

1)私は自作を使用してMySQLをインストールしているが、

Terminal screen grab

2)私はスパイダーを開いて、入力し 'securities_master' という名前のデータベースとテーブルを作成し、以下の

#!/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") 

プログラミングエラー!ダン!私はそれが楽しみのnoobsのエラーを拾っていると想像することはできませんので、時間をかけて助けてくれる人にはとても感謝します。代わりに、これらのダニですべて作成の

+0

まず、このプログラムをPythonインタプリタで行ごとに手動で実行して、何が起こっているのかを知り、Web URLが正しくフェッチされていることを確認してください。 –

+0

助けてくれてありがとう、私はSQLiteを使用して変更し、それはチュートリアルと並んで行ごとに並んでいますが、それだけでは機能しませんが、実際に私が今見ていることを実際に理解しています。とても有難い –

答えて

0

「トライバッククォートの `これに

変更final_str:

SHOW TABLES;引用符を示し
final_str = "INSERT INTO symbol (%s) VALUES (%s)" % (column_str, insert_str) 
0

キーがされていることを(別名『カーリー』引用符)代わりに...よく...何もない。そのクエリの結果は、引用符なしでテーブル名を表示する必要があります。つまり、偶然にが作成されました。「中かっこ」の引用符を持つテーブルが作成されました。例えば

final_str = "INSERT INTO `‘symbol’` (%s) VALUES (%s)" 

または引用符なしでテーブルを再作成:

show tables example

あなたのオプションは、このようなコードを変更することがあります。

2番目を実行します。

最初にウェブサイトや文書からテーブル名をコピーしていると思いますが、なぜ「まっすぐ」引用符(')の代わりに「中かっこ」引用符があるのか​​を説明します。ストレート引用符はほとんどのプログラミング言語で文字列を意味しますが、中括弧は実際にはプログラミングでは使用されません。テキストではワープロやWYSIWYGエディタで置き換えられます。

関連する問題