32
32

More than 5 years have passed since last update.

【データサイエンス基礎】pythonでcsvからmysqlに保存してみた

Last updated at Posted at 2015-05-24

データサイエンスたるものデータをRDBにセットするのはそりゃ必須でしょうということなので。

ちなみに前記事

一応シリーズ続き。今後も取得したデータで解析とかも続けて書いていく予定。(予定)

今回はcsv上のデータをmysqlのtableに入れるまでをやります。

csvからdbに入れるだけなので、流れはよくある
- dbセットする
- csvをparseして
- mysqlにつないで
- csvのrowデータを持ってsqlたたく
ていう感じ。
python初心者かつ普段railsでクエリ楽してる僕がそれぞれ調べつつやってみたというやつです。

mysqlに今回使うuserとかdbとかセット

普通に基本的なmysqlですね。
- create user
- create db
- create table
で今回csv入れるtabeを作る。このへんわからない人はこの記事参考(mysql 初めからtable作成まで一連のコマンド備忘録)

csvをparse

import csv

でcsv moduleいれて、

with open('path/to/csvfile.csv') as csvfile:
  reader = csv.reader(csvfile)

csvfile<open file 'path/to/csvfile.csv', mode 'r' at 0x1098da030>オブジェクトが入り、readerにcsvfileのそれぞれのlineを繰り返す(iterateする)オブジェクトが入る。

Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

こちらより

headerをskip

csvfileのheaderを含みたくなかったので、headerはskipした。

  next(reader, None)

next()の説明はここ

next(iterarot[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

一行ずつ順番に見ていく

  for row in reader:
        # 一行ずつdbに入れる

mysqlにつなぐ

import mysql.connector

でmoduleいれて、

dbcon = mysql.connector.connect(
  database=inifile.get("database", "db"),
  user=inifile.get("database", "user"),
  password=inifile.get("database", "password"),
  host=inifile.get("database", "host")
)
dbcur = dbcon.cursor()
dbcur.execute('INSERT INTO table名 (col名, col名) VALUES(%s, "%s")' % ('v1', 'v2'))
dbcon.commit()

で入る。空気読めばだいたいわかる(すみませんそれぞれのmoduleのmethodの動きしっかり調べるのは面倒になりました)。commitで実際にsql実行されてる感じとか。理由の一つとしては、多分sql複数ある時とか何回もmysql繋いで切って、を繰り返すより一回繋いだ時に一気にsql叩いた方が効率良いからまとめてんのかな。(憶測)

以上まとめて

こんな感じ。(table名とかconfigは今回の僕の環境のものなので適当に変えてください。)

import mysql.connector
import csv
import ConfigParser

inifile = ConfigParser.ConfigParser()
inifile.read("config/database.ini")
dbcon = mysql.connector.connect(
  database=inifile.get("database", "db"),
  user=inifile.get("database", "user"),
  password=inifile.get("database", "password"),
  host=inifile.get("database", "host")
)
dbcur = dbcon.cursor()
with open('RCdata/chefmozaccepts.csv') as csvfile:
  reader = csv.reader(csvfile)
  next(reader, None)
  for row in reader:
    dbcur.execute('INSERT INTO restaurants_payments_methods (restaurant_id, payment_method) VALUES(%s, "%s")' % tuple(row))
dbcon.commit()

補足

そのほかpython知らなかった僕が調べたこと。

pythonには()で囲まれるタプルなる組み込み型がある。

こちらよりタプルとリストの違い

just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

タプル知らなかったー。

32
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
32