所以我正在尝试将Python连接到MySQL。我正在努力开发一个算法交易系统。目前,我正在尝试使用S& P500上列出的公司符号填充名为 symbols 的表格。 MySQL有正确的密码,但MySQL似乎并不这么认为。它似乎认为密码是'是'......?请参阅下面我的python脚本中的代码。
#!/usr/bin/python
# -*- coding: utf-8 -*-
#insert_symbols.py
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 = 'sec_user'
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))
When I run this script, I get the following output:
Traceback (most recent call last):
File "./symbols_mysql.py", line 82, in <module>
insert_snp500_symbols(symbols)
File "./symbols_mysql.py", line 63, in insert_snp500_symbols
host=db_host, user=db_user, passwd=db_pass, db=db_name
File "/home/matt/.local/lib/python2.7/site-packages/MySQLdb /init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/home/matt/.local/lib/python2.7/site-packages/MySQLdb /connections.py", line 204, in __init__
gs,** kwargs2) _ mysql_exceptions.OperationalError:(1045,“拒绝访问用户'sec_user'@'localhost'(使用密码:YES)”)
我真的很抱歉这是多么的混乱。我已经环顾四周试图找到某种答案,但无济于事。我对Python很好,但是,对我来说MySQL仍然是一个新的野兽!非常感谢任何帮助!!!!
由于