1. はじめに
今回はPythonでMySQLを扱う方法を記載する.
実行環境
OS
- macOS Catalina 10.15.2
macで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
"""