質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

3回答

963閲覧

pythonからMySQLへのデータの挿入(オブジェクトエラー)

RenNearco

総合スコア13

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2018/07/28 09:02

編集2018/07/28 09:32

前提・実現したいこと

このページのデータをスクレイピングし、MySQlへ挿入したいのですが、
挿入するところで以下のエラーメッセージが発生します。

発生している問題・エラーメッセージ

Traceback (most recent call last): File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 377, in c md_query raw_as_string=raw_as_string) _mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values (742976, ディープインパクト, Deep Impact, JPN, 繁殖, サラ, ' at line 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "horse_q.py", line 76, in <module> profile['市場取引'], profile['繋養先'], profile['種付料'])) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 264, in execu te raw_as_string=self._raw_as_string) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 380, in c md_query sqlstate=exc.sqlstate) mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for th e right syntax to use near 'values (742976, ディープインパクト, Deep Impact, JPN, 繁殖, サラ, ' at line 1

修正

以下のように%をつけました。
単純にSQLが間違っているのでしょうか。

該当のソースコード

未完ですが、以下ソースコードです。

python

1import mysql.connector 2import urllib.request, urllib.error 3from bs4 import BeautifulSoup 4import re 5 6connect = mysql.connector.connect( 7 host='localhost', user='root', passwd='********', db='horse_test', charset='utf8') 8cursor = connect.cursor() 9 10# プロフィールの項目 11profile_key_list = ['登録', '品種', '性別', '生年月日', '馬主', '毛色', 12 '調教師', '生産牧場', '産地', '戦績', '総賞金', 13 '市場取引', '繋養先', '種付料'] 14profile_dict = {i: [] for i in profile_key_list} 15profile = {i: [] for i in profile_key_list} 16 17start = 742976 18stop = start 19 20while start <= stop: 21 22 url = urllib.request.urlopen('http://www.jbis.or.jp/horse/' + '{0:010d}'.format(start) + '/') 23 html = BeautifulSoup(url, 'lxml') 24 25 try: 26 name_ja = html.find('h1', class_='hdg-l1-02').text 27 name_en = html.find('div', class_='sup').text.strip().splitlines()[0] 28 if name_ja == '_________': 29 name_ja, name_en = 'unknown', 'unknown' 30 elif '現在' in name_en: 31 name_en = None 32 except: 33 name_ja,name_en = None, None 34 35 try: 36 country = re.search(re.compile(r'(.+?)'), (name_ja + name_en))[0] 37 except: 38 country = 'unk' 39 name_ja, name_en = name_ja.replace(country, ''), name_en.replace(country, '') 40 if name_en == '': 41 name_en = None 42 country = country.replace('(', '').replace(')', '') 43 44 try: 45 profile_table_html = html.find_all('table', class_='tbl-data-05') 46 profile_table_text = profile_table_html[0].text.replace(' (アラブ血量)', '\n') 47 profile_list = [i for i in profile_table_text.splitlines() if i not in ['', u'\xa0']] 48 except: 49 profile_list = [] 50 51 key = profile_list[0] 52 assert key in profile_list 53 54 for i in profile_list[1:]: 55 if i in profile_dict: 56 key = i 57 elif i.strip() == '写真': 58 break 59 else: 60 profile_dict[key].append(i.strip().replace(u'\u3000', '')) 61 62 for i in profile_dict: 63 profile[i] = ''.join(profile_dict[i]) 64 65 cursor.execute('insert into horse \ 66 (id, name_ja, name_en, country, \ 67 state, kind, sex, date_of_birth, owner, coat_color, \ 68 trainer, breeding_farm, producting_area, past_performance, earning, \ 69 market, maintin_farm, stud_fee \ 70 values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' % 71 (start, name_ja, name_en, country, 72 profile['登録'], profile['品種'], profile['性別'], 73 profile['生年月日'], profile['馬主'], profile['毛色'], 74 profile['調教師'], profile['生産牧場'], profile['産地'], 75 profile['戦績'], profile['総賞金'], 76 profile['市場取引'], profile['繋養先'], profile['種付料'])) 77 78 start += 1 79 80# 保存 81connect.commit() 82connect.close()

試したこと

エラーメーセージで検索して色々調べたんですが、
調べ方が悪いのか原因が分かりませんでした。
「こう調べれば良いよ」等だけでも教えていただきたいです。

以上、よろしくお願い致します。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

SQLは詳しくないですが、、、

'insert into horse
(id, name_ja, name_en, country,
state, kind, sex, date_of_birth, owner, coat_color,
trainer, breeding_farm, producting_area, past_performance, earning,
market, maintin_farm, stud_fee \

id の前の括弧が閉じてないです。
stud_fee の次に 閉じ括弧 ')' が来るのではないでしょうか?

投稿2018/07/28 10:14

pepperleaf

総合スコア6383

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

RenNearco

2018/07/31 17:10

stud_feeの次に)を付けても同様のエラーが出てしまいます。
guest

0

註: 編集前の質問に対する回答です。

%を忘れてませんか?

Python

1>>> s1 = 'spam' 2>>> s2 = 'ham' 3>>> s3 = 'egg' 4>>> 5>>> '1 %s 2 %s 3 %s' % (s1, s2, s3) 6'1 spam 2 ham 3 egg' 7>>> 8>>> '1 %s 2 %s 3 %s' (s1, s2, s3) 9Traceback (most recent call last): 10 File "<stdin>", line 1, in <module> 11TypeError: 'str' object is not callable

投稿2018/07/28 09:05

編集2018/07/28 10:15
LouiS0616

総合スコア35660

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

RenNearco

2018/07/28 09:38

ありがとうございます。 修正しましたが、別のエラーが出てしまいました。
LouiS0616

2018/07/28 09:45

すみません、SQLについては全然わかりません。 他の回答が付くのを待つか、新たに質問を立ててください。
RenNearco

2018/07/28 09:52

承知致しました。 いつも回答していただきありがとうございます。
guest

0

自己解決

valuesの行を下記の通りにしたら無事挿入できました。
旧:values (%s, %s, …… %s, %s)'** %**
新:values (%s, %s, …… %s, %s)',

python

1cursor.execute('insert into horse \ 2 (id, name_ja, name_en, country, \ 3 state, kind, sex, date_of_birth, owner, coat_color, \ 4 trainer, breeding_farm, producting_area, past_performance, earning, \ 5 market, maintin_farm, stud_fee) \ 6 values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', 7 (start, name_ja, name_en, country, 8 profile['登録'], profile['品種'], profile['性別'], 9 profile['生年月日'], profile['馬主'], profile['毛色'], 10 profile['調教師'], profile['生産牧場'], profile['産地'], 11 profile['戦績'], profile['総賞金'], 12 profile['市場取引'], profile['繋養先'], profile['種付料']))

回答してくださった方ありがとうございました。
(о´∀`о)(´∇`)

投稿2018/07/31 18:02

RenNearco

総合スコア13

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問