标签:通过 cursor cep name llb 输入 数据库连接 命令行 ble
conn = MySQLdb.connect(#建立一个连接。命名为conn host ='localhost',#主机 user ='root',#本地用户 passwd ='',#password db ='mysql_test_db',#连接数据库名 ) conn.close()
cur = conn.cursor() cur.close()注:当然游标能够定义多个
sql = "select * from students" cur.execute(sql) print cur.fetchall()sql中存放的符合MySQL语法规则的SQL语句,cur调用execut方法。将SQL语句传给DBMS运行,返回值用cur指向;
sql="select aid,sum(dollars) from orders where cid=%s group byaid" cur.execute(sql,[agent])比方须要依据输入的agent值,构成完整的SQL语句,当然还能够是多个參数:
def connect_width(text, width): stext =text iftype(text)==int or type(text)==long:#假设是数字型须要转为字符型 stext = str(text) return"%-*s"%(width,stext) def Print_MySqldb_Result(cur): str_result="| " row1="" array_lenth=[] iflen(cur.fetchall())==0: print "cur is null,check your sql select" else: for field_desc in cur.description: if len(field_desc[0])>field_desc[2]: array_lenth.append(len(field_desc[0])) else: array_lenth.append(field_desc[2]) text=connect_width(field_desc[0],field_desc[2]) str_result=str_result+text+" |" lenth=len(str_result) for i in range(lenth): if i==0: row1=row1+"+" else: if i==lenth-1: row1=row1+"+" else: row1=row1+"-" print row1 print str_result print row1 for i in cur: row2="| " k=0 for j in i: text=connect_width(j,array_lenth[k]) row2=row2+text+" |" k=k+1 print row2 print row1格式化打印效果:
importMySQLdb def connect_width(text, width): stext =text iftype(text)==int or type(text)==long:#假设是数字型须要转为字符型 stext = str(text) return"%-*s"%(width,stext) def Print_MySqldb_Result(cur): str_result="| " row1="" array_lenth=[] iflen(cur.fetchall())==0: print "cur is null,check your sql select" else: for field_desc in cur.description: if len(field_desc[0])>field_desc[2]: array_lenth.append(len(field_desc[0])) else: array_lenth.append(field_desc[2]) text=connect_width(field_desc[0],field_desc[2]) str_result=str_result+text+" |" lenth=len(str_result) for i in range(lenth): if i==0: row1=row1+"+" else: if i==lenth-1: row1=row1+"+" else: row1=row1+"-" print row1 print str_result print row1 for i in cur: row2="| " k=0 for j in i: text=connect_width(j,array_lenth[k]) row2=row2+text+" |" k=k+1 print row2 print row1 #print "print ok" conn=MySQLdb.connect( host='localhost', user='root', passwd='', db='mysql_test_db', # charset='utf8', ) cur=conn.cursor() while 1: agent =input("Please input cid,input 1 to exit:\n") ifagent==1: break else: #agent = "C1" sql="select aid,sum(dollars) from orders where cid=%s group byaid" cur.execute(sql,[agent]) print "agent_dollars with cid='%s'"%agent Print_MySqldb_Result(cur) #print('run ok') conn.commit() cur.close() conn.close()执行结果:
标签:通过 cursor cep name llb 输入 数据库连接 命令行 ble
原文地址:http://www.cnblogs.com/lytwajue/p/7123630.html