2017-01-23 3 views
0

이 제목은 이미 다룰 수 있습니다. 그렇다면, 사과드립니다. 데이터베이스 ("for"및 "while"루프 포함)에서 행을 가져 와서 콘솔에서 스크립트를 실행할 때 문제가 있습니다.Py : 데이터베이스에서 가져 오기 및 콘솔에서 스크립트를 실행할 때 제한

데이터베이스에서 엄청난 양의 행을 가져와야하고 사용자 ID를 삽입 할 수 있도록 스크립트를 작성하므로 클라이언트 및 상태에 대한 계정 ID를 가져옵니다. Eclipse에서 스크립트를 실행하면 DB에서 전체 출력을 가져 오는 것을 깨달았습니다. 콘솔에서 스크립트를 실행할 때 행 제한이 있습니다. 그래서, 나는 "행이 없음"루프가 있는지 알고 싶습니다 ... 왜 내 행이 될 경우 없음 데이터베이스에 더 많은 행이 있습니까 ??

기타 :이 문제를 해결해야합니다. 아무리. 전체 목록을 로컬 파일에로드하는 것을 선호합니다 (가능한 경우). 하지만, 다른 방법이 없다면 ... 좋아, 제발 도와주세요 !! 이것은 나의 본보기이다. 이 같은 prettytable 모듈에서 제공 from_db_cursor() 사용하여 시도 할 수 너무 많은 코드를 수정하지 않고

#!/usr/bin/env python3 
# encoding: utf-8 

import configparser 
import pymysql 
from prettytable import PrettyTable 

conn = pymysql.connect(host=host, user=user, passwd=password, db=database) 

print() 
userid = input('Insert User ID(s) > ') # userid is a list of 2000 users in comma-separated format 
userids = userid.replace(" ", "").replace("'", "").replace(",", "','") 
cur = conn.cursor() 
cur.execute(""" SELECT user_ID, account_ID, status FROM Account WHERE user_ID IN ('%s'); """ % userids) 
rows = cur.fetchall() 

table = PrettyTable(["user_ID", "account_ID", "status"]) 
table.padding_width = 1 

for line in rows: 
    user_ID = str(line[0]) 
    account_ID = str(line[1]) 
    status = str(line[2]) 
    table.add_row([user_ID, account_ID, status]) 

print() 
print(table) 
conn.close() 
print() 
print() 
exit() 

답변

0

:

#!/usr/bin/env python3 

import pymysql 
from prettytable import from_db_cursor 

conn = pymysql.connect(host=host, user=user, passwd=password, db=database) 

userid = input('Insert User ID(s) > ') # userid is a list of 2000 users in comma-separated format 
userids = userid.replace(" ", "").replace("'", "").replace(",", "','") 
cur = conn.cursor() 
cur.execute(""" SELECT user_ID, account_ID, status FROM Account WHERE user_ID IN ('%s'); """ % userids) 

table = from_db_cursor(cur, padding_width=1) 

print(table) 
conn.close() 

그러나이 prettytable 내 생각의 소스 코드를보고인지는 변경되지 않습니다 이 상황은 코드에서 명시 적으로 수행 한 작업을 수행 한 이후로 많이 발생합니다. 아마 더 잘 작동 것이 무엇


대신 모든 행을 가져 와서 추가 그들을 통해 반복의 table에 1 번에 1 행을 추가하는 것입니다. 같은 : 당신은 Prettytable부터 문자열 값으로 행 요소를 변환 할 필요가 없습니다

#!/usr/bin/env python3 

import pymysql 
from prettytable import PrettyTable 

conn = pymysql.connect(host=host, user=user, passwd=password, db=database) 

userid = input('Insert User ID(s) > ') # userid is a list of 2000 users in comma-separated format 
userids = userid.replace(" ", "").replace("'", "").replace(",", "','") 
cur = conn.cursor() 
cur.execute(""" SELECT user_ID, account_ID, status FROM Account WHERE user_ID IN ('%s'); """ % userids) 
row = cur.fetchone() 

table = PrettyTable(["user_ID", "account_ID", "status"], padding_width=1) 

while row is not None: 
    table.add_row(row) 
    row = cur.fetchone() 

print(table) 
conn.close() 

는 내부적으로한다.


하지만 코드를 단순화하고 더 파이썬 수 있도록 다양한 기능을 활용할 수 있습니다 :

  • 나는 re.sub()을 사용하고 있습니다 :

    #!/usr/bin/env python3 
    
    import re 
    import pymysql 
    from prettytable import PrettyTable 
    
    userid = input('Insert User ID(s) > ') # userid is a list of 2000 users in comma-separated format 
    userids = re.sub("[ ']", "", userid).replace(",", "','") 
    
    table = PrettyTable(["user_ID", "account_ID", "status"], padding_width=1) 
    
    with pymysql.connect(host=host, user=user, passwd=password, db=database) as cur: 
        cur.execute("""SELECT user_ID, account_ID, status FROM Account WHERE user_ID IN ('%s'); """ % userids) 
    
        map(table.add_row, cur) 
    
    print(table) 
    

    이 버전에서 일부는 대체 할 수 있습니다 (일부는 지나치게 과장되어 있지만 나중에 유용 할 수 있습니다)

  • Pymysql 연결 implements 커서를 직접 제공하는 context manager.
  • Pymysql 커서는 provide이고 iterator이므로 map()과 함께 사용하면 결과를 신경 쓰지 않아도 모든 행을 이동할 수 있습니다.