일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- crud
- 반복문
- 자바
- Homebrew
- ddit
- 객체지향
- jsp
- JDBC
- python
- servlet
- 맥
- 단축키
- Android
- 배열
- API
- html
- 자바문제
- 컬렉션프레임워크
- Java
- spring
- nodejs
- pyqt
- 대덕인재개발원
- Oracle
- FastAPI
- 생활코딩
- Mac
- 이클립스
- Error
- ibatis
Archives
- Today
- Total
romworld
Python 18 - FastAPI (MS SQL연동) 본문
전에 작성해둔 MS SQL과 연동하는 파일을 참고한다.
<mssql_select>
# pymssql 패키지 import
import pymssql
# MSSQL 접속
conn = pymssql.connect(server="", user="sa", password="", database="python", charset='utf8')
# Connection 으로부터 Cursor 생성
cursor = conn.cursor()
# SQL문 실행
cursor.execute('SELECT * FROM emp;')
# 데이타 Fetch하여 출력
list = cursor.fetchall()
print(list)
cursor.close()
# 연결 끊기
conn.close()
<myfast01.py>
from fastapi import FastAPI,Form,Request
import uvicorn
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from scrapy.http.response.html import HtmlResponse
import pymssql
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/emp",response_class=HtmlResponse)
async def emp(request:Request):
conn = pymssql.connect(server="", user="sa", password="", database="python", charset='utf8')
cursor = conn.cursor()
cursor.execute('SELECT * FROM emp;')
list = cursor.fetchall()
cursor.close()
conn.close()
return templates.TemplateResponse("emp.html", {"request":request,"list":list})
if __name__ == '__main__':
uvicorn.run(app, host="localhost", port=8000)
1. 먼저 pymssql 를 import해준다.
2. 위의 DB연동을 참고하여 로직을 emp 메소드 안에 넣어준다.
<emp.html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
{{list}}
<table border="1px">
<tr>
<td>사번</td>
<td>이름</td>
<td>성별</td>
<td>주소</td>
</tr>
{% for i in list %}
<tr>
<td>{{i[0]}}</td>
<td>{{i[1]}}</td>
<td>{{i[2]}}</td>
<td>{{i[3]}}</td>
</tr>
{%endfor%}
</table>
</body>
</html>
반복문을 이용해 list를 출력해주면
원래 생성되어 있는 emp 테이블의 데이터가 출력된다.
'Python' 카테고리의 다른 글
Python 20 - CRUD (emp 테이블) (0) | 2023.01.06 |
---|---|
Python 19 - DAO 만들기 (0) | 2023.01.06 |
Python 17 - FastAPI (post, forward방식, Jinja2) (0) | 2023.01.05 |
Python 16 - FastAPI(프레임워크) (0) | 2023.01.04 |
Python 15 - SQLite (데이터 베이스 연동) / Anaconda.navigator (라이브러리 관리) (0) | 2023.01.04 |
Comments