본문 바로가기
MySql

MySQL Python의 데이터베이스에서 CSV 파일을 어떻게 생성합니까?

by 베이스 공부 2020. 11. 7.
반응형

"clients"라는 Sqlite 3 및 / 또는 MySQL 테이블이 있습니다.

Python 2.6을 사용하여 헤더가있는 Clients100914.csv라는 csv 파일을 어떻게 생성합니까? 엑셀 방언 ...

Sql execute : select *는 테이블 데이터 만 제공하지만 헤더가있는 전체 테이블을 원합니다.

테이블 헤더를 가져 오기 위해 레코드 세트를 생성하는 방법. 테이블 헤더는 파이썬으로 작성되지 않은 SQL에서 직접 가져와야합니다.

w = csv.writer(open(Fn,'wb'),dialect='excel')
#w.writelines("header_row")
#Fetch into sqld
w.writerows(sqld)

이 코드는 파일이 열려 있고 헤더가 없습니다. 또한 파일을 로그로 사용하는 방법을 알 수 없습니다.

 

해결 방법

 

import csv
import sqlite3

from glob import glob; from os.path import expanduser
conn = sqlite3.connect( # open "places.sqlite" from one of the Firefox profiles
    glob(expanduser('~/.mozilla/firefox/*/places.sqlite'))[0]
)
cursor = conn.cursor()
cursor.execute("select * from moz_places;")
#with open("out.csv", "w", newline='') as csv_file:  # Python 3 version    
with open("out.csv", "wb") as csv_file:              # Python 2 version
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow([i[0] for i in cursor.description]) # write headers
    csv_writer.writerows(cursor)


 

참조 페이지 https://stackoverflow.com/questions/3710263

 

 

반응형

댓글