LoginSignup
4
9

More than 5 years have passed since last update.

Pythonを使ってMysqlを操作する

Posted at

はじめに

Pythonを使ってMySQLのデータベースにデータを入れていくための手法です。
今回はデータとしてTweetデータを使用しています。

こちらのTwitter DeveloperのページからTwitterAPIの登録申請を行うことができます。

登録申請の方法は本記事では割愛します。

環境

Mac OS Mojava バージョン10.14
Python 3.6.0
MySQL 5.6.41

環境構築

Pythonのインストール
MacにおけるPythonの環境構築は下記の記事にまとめていますのでご参考ください
[Macで1からPythonの環境構築をしていく]

MySQLのインストール
上記の[Macで1からPythonの環境構築をしていく]の記事内でも記載しているよう、Homebrewをインストールしておきます。

  • 下記のコマンドでHomebrewをアップデート
$ brew update
  • 次にMySQLをインストールします
$ brew install mysql
  • これでMySQLのインストールは完了しているので、MySQLのサーバーを下記のコマンドで立ち上げます
$ mysql.server start

Starting MySQL
. SUCCESS! 
  • 上記のようにSUCCESS!と表示されていれば問題なくMySQLが起動している状態ですので、ここからMySQLを起動していきます。
$ mysql -uroot

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 476
Server version: 5.6.41 Homebrew

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
  • rootユーザでのmysqlの起動に成功したので次はrootのパスワードを設定します。
mysql> update mysql.user set password=password('root用の任意パスワード') where user = 'root';
mysql> flush privileges;
mysql> exit;
  • パスワードが設定できているか確認するためもう一度mysqlを起動します
$ mysql -uroot -p
Enter password:  ←ここに先ほど設定したパスワードを入力 

データベースの作成

Tweetデータを入れていくためのデータベースを作成していきます。

mysql> CREATE DATABASE tweetdata DEFAULT CHARACTER SET utf8mb4;
Query OK, 1 row affected (0.04 sec)
  • 今回はTweetデータをデータベースに入れるため、絵文字を含む可能性があります。よって文字コードはutf8mb4としてデータベースを作成します。

必要なライブラリのインストール

MySQLdbのインストール
PythonからMysqlに接続するためのライブラリです。

 $ sudo pip install MySQL-python

requests_oauthlibのインストール
OAuth認証のためのPythonのライブラリです。

$ sudo pip install requests requests_oauthlib

実装

今回は単語を入力し、その単語を含むツイート内容と発言したユーザ名を取得しMysqlに入れていきます。

config.py
CONSUMER_KEY = "*********************"
CONSUMER_SECRET = "*********************"
ACCESS_TOKEN = "*********************"
ACCESS_TOKEN_SECRET = "*********************"

Twitter Developerのページのサイトよりご自身のキーを入力してください。

tweet.py

# -*- coding:utf-8 -*-

import MySQLdb 
import json, config
from requests_oauthlib import OAuth1Session

CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
twitter = OAuth1Session(CK, CS, AT, ATS)

#自分のローカルのMysqlへの接続 passwdには先ほど設定したrootのパスを入力
conn = MySQLdb.connect(host='localhost',user='root',passwd='######',db='tweetdata', charset='utf8mb4')

#テーブルの作成(2回目以降の実行では不要)
c.execute('''
     CREATE TABLE sample(
       id integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
       name text,
       content text
     )
 ''')  

url = "https://api.twitter.com/1.1/search/tweets.json"

print("何を調べますか?")
keyword = input('>> ')
print('----------------------------------------------------')

#10個のツイートデータを取得
params = {'q' : keyword, 'count' : 10}

req = twitter.get(url, params = params)

if req.status_code == 200:
    search_timeline = json.loads(req.text)
    for tweet in search_timeline['statuses']:
        print(tweet['user']['name'] + '::' + tweet['text'])
        print(tweet['created_at'])
        print('----------------------------------------------------')
        #ユーザ名,ツイートの内容をMysqlに入れていく
        c.execute('INSERT INTO sample (name,content) VALUES(%s,%s)',(tweet['user']['name'],tweet['text']))
        conn.commit()
else:
    print("ERROR: %d" % req.status_code)


conn.close()

ツイートデータを取得し、Mysqlに入れていく事ができました。

4
9
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
4
9