[0401 개발일지] 데이터베이스 연동

이지원·2022년 4월 1일
0

1. 학습한 내용

플라스크 앱에 데이터베이스를 연동하는 법

# SQLite DB 연결
conn = sqlite3.connect("test.db")
 
# Connection 으로부터 Cursor 생성
cur = conn.cursor()
 
# SQL 쿼리 실행
cur.execute("select * from customer")
 
# 데이타 Fetch
rows = cur.fetchall()
for row in rows:
    print(row)
 
# Connection 닫기
conn.close()
@app.route("/")
def index():
  return template('<h2>Welcome</h2>Hello, WEB!')

@app.route("/read/<int:id>/")
def read(id):
  conn = sqlite3.connect('db.sqlite3')
  cs = conn.cursor()
  cs.execute('SELECT * FROM topics WHERE id=?', (id,))
  topic = cs.fetchone()
  conn.close()
  title = topic[1]
  body = topic[2]
  return template(f'<h2>{title}</h2>{body}', id)

@app.route('/create/')
def create():
  content = '''
    <form action="/create_process/" method="POST">
      <p><input type="text" name="title" placeholder="title"></p>
      <p><textarea name="body" placeholder="body"></textarea></p>
      <p><input type="submit" value="create"></p>
    </form>
  '''
  return template(content)

@app.route('/create_process/', methods=['POST'])
def create_process():
  title = request.form['title']
  body = request.form['body']
  conn = sqlite3.connect('db.sqlite3')
  cs = conn.cursor()
  cs.execute('INSERT INTO topics (title, body) VALUES(?,?)',(title,body))
  id = cs.lastrowid
  conn.commit()
  conn.close()
  return redirect(f'/read/{id}/')

2. 어려웠던 점

3. 해결방법

4. 학습소감

일주일 동안 배운 자바와 파이썬을 마무리를 하게 되었다.
이해못하고 넘어간 부분도 있고 (많고) 파이썬 파트는.. 부족한 부분이 많지만
이고잉 강사님의 수업은 재미있었다.
옛날 혼자서 html, css를 독학해볼까하며 구글링하다가
생활코딩이라는 사이트를 알게되었었는데 사이트를 제작한
프로그래머님이 직접 강의를 해주시는 기회가 생겨 좋았다.

profile
ai스쿨

0개의 댓글