2
1

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 5 years have passed since last update.

Pythonデータベース連携(index.py)

2
Posted at

前回の続きで、これまで蓄積した全てのデータを表示させるために、こんな感じでindex.pyファイルをつくりました。

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import io
import sqlite3
import cgi

# データベースに接続する
conn = sqlite3.connect('sample.db')
c = conn.cursor()

htmlTable = ""

try:
   c.execute("select * from users;")
except sqlite3.Error as e:
   print("ERROR:", e.args[0])

rows = c.fetchall()

# データベースから値を取り出す
if not rows:
   htmlTable = "No Data"
else:
   for row in rows:
       htmlTable += str(row[0]) + "|" + str(row[1]) + "|" + str(row[2]) + "|" + str(row[3]) + "</br>"

c.close()

# 以下のコードを書かないと、htmlとして読み込んでもらえない。
print("Content-type: text/html; charset=utf-8")

# htmlの部分。printでHTMLコードを表示させることで、ブラウザがHTMLコードとして認識してくれる。
print(
(
'''
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>学生一覧画面</title>
  </head>
  <body>


<h1>学生一覧</h1> <br> <br>

%s

  <a href="input.py">自分の学生情報を記入する</a>
  </body>
</html>
'''
) % htmlTable )
スクリーンショット 2019-06-15 17.28.05.png

こんな感じで表示されます!ぜひみなさんもやってみてください!

2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?