JJC's 테크니컬 다이어리

Py SQLite 샘플-CSV읽기/텍스트파일사용/select/delete문 처리 본문

SQLite

Py SQLite 샘플-CSV읽기/텍스트파일사용/select/delete문 처리

털털한JJC 2009. 10. 29. 16:22
#!/opt/bin/python
# -*- coding: cp949 -*-
import sys
sys.path.append('/opt/lib/python2.4/site-packages')
from pysqlite2 import dbapi2 as sqlite
import csv, os, string

print "Content-Type: text/html"
print
datafile ='./detail.csv'
outfile = './' +'insertsql.sql'

reader = csv.reader(file(datafile),dialect='excel')
row = reader.next()

# Create insert SQL statement
rc = 0
sqlfile=open(outfile,'w')
# Create a connection to the database file "mydb":
con = sqlite.connect("mydb")
cur = con.cursor()

for row in reader:
#  print row
  rc = rc + 1
  if row[1]=='':
    continue
  # Execute the SELECT statement:
  wwappno=string.strip(row[1])
  if len(row[0])<10:
      continue;
  cur.execute("select appno from credituse where appno=?",(wwappno,))

#select result yes then continue;
  if cur.fetchall():
      stmt="delete from credituse where appno='"+wwappno
      stmt=stmt+"';\n"
      print stmt
      sqlfile.write(stmt)
 
#  if cur==[]:
#    continue;
  stmt='INSERT INTO credituse VALUES('
  for i in range(8):
    fld = string.strip(row[i])
    if i==0:
      fld = string.replace(row[i],'-','.')
    if i==6:
      fld = string.replace(row[i],',','')
    stmt=stmt+"'"+fld+"'"
    if i<7:
      stmt=stmt+ ','
  stmt=stmt+ ');\n'
  print stmt
  sqlfile.write(stmt)
sqlfile.close  
print "<br>"
print "<br>"
print "업로드가 완료되었으며"
print "<br>"
print "데이타베이스에 자료를 넣을 준비가 완료되었습니다."
print "<br>"
print "아래 자료입력을 클릭하시면 자료가 입력됩니다."
print "<br>"
print "<a href=insert.py>자료입력</a>"
#create table credituse (usedate,appno primary key,cardno,storename,paytype,paymonth,price,accept);