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.

Python3: MariaDB のデータを読む (Read)

Posted at

プログラム

フォルダー構造

$ tree -a
.
├── .env
├── config_mariadb.py
└── maria_read.py

.env
config_mariadb.py
はこちら
Python3: MariaDB のバージョンを表示

maria_read.py
#! /usr/bin/python
#
#	maria_read.py
#					Feb/22/2023
#
import sys
import mariadb
#
from config_mariadb import config_mariadb_proc
# ----------------------------------------------------------------
def dict_display_proc(dict_aa):
	for key in sorted(dict_aa.keys()):
		if ((key != '_id') and (key != '_rev')):
			unit = dict_aa[key]
			name = unit['name']
			str_out = str(key) +"\t"+ str(name)
			str_out += "\t" + str(unit['population'])
			str_out += "\t" + str(unit['date_mod'])
			print(str_out)
# ----------------------------------------------------------------
def	sql_to_dict_proc	(cursor):
	dict_aa = {}
	sql_str=u"select id, name, population, date_mod from cities order by id"
	cursor.execute (sql_str)
	rows = cursor.fetchall ()
	for row in rows:
		if (row['id'][0] == "t"):
			unit_aa = {}
			unit_aa['name'] = row['name']
			unit_aa['population'] = row['population']
			unit_aa['date_mod'] = str (row['date_mod'])
			dict_aa[row['id']] = unit_aa
#
	return	dict_aa
#
# ----------------------------------------------------------------
sys.stderr.write ("*** 開始 ***\n")
#
host,user,password,data_base = config_mariadb_proc()
conn = mariadb.connect(user=user, password=password, \
                              host=host,database=data_base)
#
cursor = conn.cursor (dictionary=True)
#
dict_aa = sql_to_dict_proc (cursor)
#
cursor.close ()
conn.close ()
#
dict_display_proc (dict_aa)
#
sys.stderr.write ("*** 終了 ***\n")
#
# ----------------------------------------------------------------

実行結果

$ ./maria_read.py 
*** 開始 ***
t3321	岡山	529176	2003-09-20
t3322	倉敷	791835	2003-02-15
t3323	津山	163754	2003-08-18
t3324	玉野	369172	2003-01-09
t3325	笠岡	237451	2003-03-04
t3326	井原	518397	2003-05-21
t3327	総社	248156	2003-07-23
t3328	高梁	478294	2003-10-26
t3329	新見	823751	2003-12-17
*** 終了 ***
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?