5
9

More than 3 years have passed since last update.

【初心者向け入門】PythonでMySQLを扱う

Last updated at Posted at 2019-12-30

1. はじめに

今回はPythonでMySQLを扱う方法を記載する.

実行環境

OS

  • macOS Catalina 10.15.2

macでMySQLを使えるようにする

参考:PythonでMySQLに接続する方法【初心者向け】

(前提:Pythonが使える,pipコマンドが使える,brewコマンドが使える)
1. ターミナルでpip install mysqlclientと入力し,MySQLをインストール.
2. ターミナルでbrew install mysql-connector-cと入力し,MySQLへアクセスできるようにする.

2. ソースコード

2.1. 接続と切断

#----------------
#標準ライブラリ
#----------------
#import pymysql.cursors #Raspberry Pi,Win用
import MySQLdb          #mac用

#上の方をmacで使う場合は
# pip3 install pymysql
#でインストールする必要がある


#---------
# 接続
#---------
#cnct = pymysql.connect( #Raspberry Pi用
cnct = MySQLdb.connect(  #Win,mac用
    host = "localhost",  #ホスト名
    user = "root",       #MySQLユーザ名
    password = "",       #MySQLユーザパスワード
    db = "test",         #データベース名
    charset = "utf8"     #文字コード
    )
TABLE = "test"           #テーブル名

cur = cnct.cursor()


#---------
# ここでデータベースの操作を行う
#---------


#---------
# 切断
#---------

cur.close()
cnct.close()

2.2. データの取得と表示

cur.execute("SELECT * FROM " + TABLE + ";") #SQLのコマンド
results = cur.fetchall()                    #結果をresultに格納
print("全て表示")
print(results)
print("\n")

print("1行ずつ表示")
for r in results:
    print(r) # r は配列なので,要素単位で表示する場合はインデックスを指定すれば良い.例:print(r[0])

if文でデータがあるかないかを表示したい場合

cur.execute("SELECT * FROM " + TABLE + ";")
results = cur.fetchall()
if results: #配列resultsの中にデータが存在する
    print("データあり")
    print(results)
else:       #配列resultsの中にデータが存在しない(配列が空)
    print("データなし")

2.3 データの追加

#データの追加
cur.execute("INSERT INTO " + TABLE + " " + ROW + " VALUES (%s,%s);", ("test1","test2"))
cur.execute("INSERT INTO " + TABLE + " " + ROW + " VALUES (%s,%s);", ("test3","test4"))
cnct.commit()   #データベースに加えた変更を保存.これがないとMySQLに反映されない.

2.4. データの削除

cur.execute("DELETE FROM " + TABLE + ";") #全データ削除.削除データを指定する場合は,WHERE句で指定
cnct.commit()   #データベースに加えた変更を保存.これがないとMySQLに反映されない.

2.5. 全て

#----------------
#標準ライブラリ
#----------------

#import pymysql.cursors #Raspberry Pi用
import MySQLdb


#----------------
#データベース接続
#----------------

#cnct = pymysql.connect( #Raspberry Pi用
cnct = MySQLdb.connect(
    host = "localhost",
    user = "root",
    password = "",
    db = "test",
    charset = "utf8"
    )
TABLE = "test"
ROW = "(data1,data2)" #追加するデータの列を指定するため

cur = cnct.cursor()


#----------------
#データベース操作
#----------------

#データの追加
cur.execute("INSERT INTO " + TABLE + " " + ROW + " VALUES (%s,%s);", ("test1","test2"))
cur.execute("INSERT INTO " + TABLE + " " + ROW + " VALUES (%s,%s);", ("test3","test4"))
cnct.commit()   #データベースに加えた変更を保存

#データの取得・表示
cur.execute("SELECT * FROM " + TABLE + ";")
results = cur.fetchall()
print("全て表示")
print(results)
print("\n")

print("1行ずつ表示")
for r in results:
    print(r) # r は配列なので,要素単位で表示する場合はインデックスを指定すれば良い.例:print(r[0])

"""
#データの削除
cur.execute("DELETE FROM " + TABLE + ";") #全データ削除.削除データを指定する場合は,WHERE句で指定
cnct.commit()   #データベースに加えた変更を保存


print("\n") #2行改行する.1行だけ改行する場合は print() と指定


#データの取得・表示
cur.execute("SELECT * FROM " + TABLE + ";")
results = cur.fetchall()
if results:
    print("データあり")
    print(results)
else:
    print("データなし")
"""

#----------------
#データベース切断
#----------------

cur.close()
cnct.close()



""" ターミナルでMySQL操作

MySQLの起動
$ mysql.server start

MySQL接続
$ mysql -u root

MySQLの終了
$ mysql.server stop


"""
5
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
5
9