#정리
** cs.executemany(sql,lst) #여러개의 데이터가 있는 리스트로 한 번에 더미값 넣기
#22read_sql - pandas 함수로 sql문 읽어오기
<공통 파트 : 계정생성 >> cursor 초기화 >> 체이블 생성 >
#import sqlite3
#1.connect : "파일명.db"에 커넥션을 맺겠다.
- con = sqlite3.connect("py22test.db")
#2. cursor init : pstmt 초기화
- cs = con.cursor()
#3. create table : 쿼리문 작성 - 뎁스 상관없음
- cs.execute('''create table if not exists test (num integer primary key autoincrement,name text,age integer)''')
#판다스를 이용한 SQL
<pandas 라이브러리 동적 쿼리문 - selectAll >
- sqlite로 데이터 추출후, 데이터 프레임으로 데이터 파싱
- padas 함수로 바로 sql 통신
>> print(pd.read_sql('''select * from test order by num desc''',con))
** cs.executemany(sql,lst) #여러개의 데이터가 있는 리스트로 한 번에 더미값 넣기
#22read_sql - sql문 읽어오기
<공통 파트 : 계정생성 >> cursor 초기화 >> 체이블 생성 >
#import sqlite3
#1.connect : "파일명.db"에 커넥션을 맺겠다.
- con = sqlite3.connect("py22test.db")
#2. cursor init : pstmt 초기화
- cs = con.cursor()
#3. create table : 쿼리문 작성 - 뎁스 상관없음
- cs.execute('''create table if not exists test (num integer primary key autoincrement,name text,age integer)''')
#판다스를 이용한 SQL
<sqlite 라이브러리 기본 동적 쿼리문 - selectAll ( css : cs의 결과가 여러개 ) >
css = cs.execute('''select * from test order by num desc''')
for row in css:
print(row)
<pandas 라이브러리 동적 쿼리문 - selectAll >
- sqlite로 데이터 추출후, 데이터 프레임으로 데이터 파싱
css = cs.execute('''select * from test order by num desc''')
print(pd.DataFrame(css,columns=['NUM','NAME','AGE']))
- padas 함수로 바로 sql 통신
print(pd.read_sql('''select * from test order by num desc''',con))
--예문 코드 보기--
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
#from numpy import *
#from pandas import Series,DataFrame
# >> Series,DataFrame 는 pd.Series라고 안적고, pd. 까지만 적어도 된다.
print("numpy version",pd.__version__) #pandas version check
print("---------------")
import sqlite3
print("---------------")
#1.connect : "파일명.db"에 커넥션을 맺겠다.
con = sqlite3.connect("py22test.db")
#ls 로 db생성 확인 가능
print("1.connection successed..")
#2. cursor init : pstmt 초기화
cs = con.cursor()
print("2.cursor init successed..")
#3. create table : 쿼리문 작성 - 뎁스 상관없음
cs.execute('''
create table if not exists test (
num integer primary key autoincrement,
name text,
age integer
)''')
#sqlite py22test.db ".tables" >> test확인 가능
print("3.create table successed..")
#동적 쿼리문 작성
#insert
'''
for i in range(10):
values = ("lee"+str(i),40+i) #tuple
cs.execute(\'''
insert into test(name,age) values(?,?)
\''', values)
con.commit()
'''
lst = []
sql = 'insert into test(name,age) values(?,?)'
def dummyInsert():
for i in range(10):
values = ("lee"+str(i),40+i) #tuple
lst.append(values)
cs.executemany(sql,lst) #여러개의 데이터가 있는 리스트로 한 번에 더미값 넣기
con.commit()
#dummyInsert()
print("4.insert successed..")
#sqlite3 py22test.db "select * from test"
#selectAll
#css : cs의 결과가 여러개
css = cs.execute('''
select * from test order by num desc
''')
#print(css)
#for 주석 꼭 할 것
'''for row in css:
print(row)'''
print("8.selectAll successed..")
#sqlite3 py20test.db "select * from test"
print("---------------")
print(pd.DataFrame(css,columns=['NUM','NAME','AGE']))
print("---------------")
print(pd.read_sql('''
select * from test order by num desc
''',con))
print("---------------")
cursor.close()
con.close()
'Python' 카테고리의 다른 글
[Python] 판다스(pandas)_9. 웹 데이터 추출(read_xml, read_html, BeautifulSoup) (0) | 2022.04.17 |
---|---|
[Python] 판다스(pandas)_8. 파일 쓰기/읽기 (CSV, EXCEL, JSON) (0) | 2022.04.16 |
[Python] 판다스(pandas)_7.pivot - 데이터프레임 재구성 (0) | 2022.04.16 |
[Python] 판다스(pandas)_7.concatenate - 데이터프레임 병합, groupby - 데이터 그룹바이 (0) | 2022.04.16 |
[Python] 판다스(pandas)_6.operator - 연산자, function - 데이터 프레임 함수 (0) | 2022.04.16 |