0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonからmysqlを操作する

Posted at

インストール

pip install mysql-connector-python

データベースの作成

import mysql.connector

conn = mysql.connector.connect(host='172.24.20.34', user='root', password='tmcit')
curs = conn.cursor()

curs.execute('CREATE DATABASE my_database')

curs.close()
conn.close()

レコードの全件取得

import mysql.connector

conn = mysql.connector.connect(host='172.24.20.34', user='root', password='tmcit', database='LESSON')
curs = conn.cursor()

curs.execute('SELECT * FROM LESSON_2025')
print(curs.fetchall())

curs.close()
conn.close()
curs.execute('SELECT * FROM LESSON_2025')
rows = curs.fetchall()

for row in rows:
  print (row)

データの挿入

import mysql.connector
conn = mysql.connector.connect(host='172.24.20.34', user='root', password='tmcit', database='LESSON')
curs = conn.cursor()

curs.execute('insert into LESSON_2025(LESSON_NAME, ACCEPTED_GRADE)values("理科", 2)')

##コミット作業
conn.commit()

curs.close()
conn.close()

変数を用いる場合

name="算数"
grade=2
curs.execute('insert into LESSON_2025 (LESSON_NAME, ACCEPTED_GRADE) values (%s, %s)', (name, grade))
conn.commit()

データベースの要素を取りだす

データベースから引っ張ってきたデータはタプル型に格納されて帰ってくるので、添え字で指定する事によって要素の取りだしが出来る。例:row[0]

curs.execute('SELECT LESSON_NAME FROM LESSON_2025')
rows = curs.fetchall()

for row in rows:
  print (row[0])

結果

root@shoma:/home/shoma/ED# python3 sel.py
2
kokugo
国語
算数
理科

参考サイト

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?