通过Python实现mysql查询数据库实例

#coding:utf-8
'''
Created on 2017年10月25日

@author: li.liu
'''

import pymysql
db=pymysql.connect('localhost','root','root','test',charset='utf8')
m=db.cursor()
'''
try:
    #a=raw_input('请输入sql语句'+'\n')
    m.execute('select * from student')
    a=m.fetchall()
    b=m.description
    print b
    print a
    for i in range(len(a)):
        n=''
        for j in range(len(b)):
            c=str(a[i][j])
            d=b[j][0].encode('utf-8')
            print '%s: %s\t'%(d,c),
        print '\r'
            
    
except:
    print 'SQL语句错误,请检查'
finally:
    db.close()
    
'''
while True:
    
    try:
        s=raw_input('请输入sql语句'+'\n')
        if s=='exit':break
        m.execute(s)
        a=m.fetchall()
        b=m.description
        for i in range(len(a)):
            n=''
            for j in range(len(b)):
                c=str(a[i][j])
                d=b[j][0].encode('utf-8')
                print '%s: %s\t'%(d,c),
            print '\r'
        print '\r'
    except:
        print 'SQL语句错误,请检查'

  

 

posted @ 2017-12-18 16:03  LLSix  阅读(234)  评论(0编辑  收藏  举报