自学python 第十八天 无聊中多写几次连接数据库的py (后面有个加强版 几乎打印一样格式 在最后附上图片)

版权声明:open source https://blog.csdn.net/Smith_My_/article/details/79945063
# -*- coding: utf-8 -*-
"""
Spyder Editor


This is a temporary script file.
"""
import pymysql


class MysqlDr(object):
    cnx = pymysql.connect(
                host = '192.168.153.128',
                port = 3306,
                user = 'root',
                password = 'root1',
                database = 'test',
                charset = 'utf8'
            )
conn = MysqlDr.cnx
cur = conn.cursor()
cur.execute('select version()')
data = cur.fetchone()
print('mysql version:%s' %data)


cur.execute('show databases;')
databases = cur.fetchall()


s = '''
+--------------------+
| Database           |
+--------------------+
'''
print(s)
compare = 0
#print(type(databases))
for i in range(len(databases)):
    #print(type(databases[i]))
    for j in range(len(databases[i])):
        #print('| ',databases[i][j].ljust(20),'|')
        #print(len(databases[i][j]))
        if(compare <= int(len(databases[i][j]))):
            compare = int(len(databases[i][j]))
        else:
            pass
        #print(compare)
        print('|',databases[i][j].ljust(compare),'|')
        


end = '''
+--------------------+
'''
print(end)

conn.close()

输出:

runfile('C:/Users/苏微/.spyder-py3/temp.py', wdir='C:/Users/苏微/.spyder-py3')
mysql version:5.6.39


+--------------------+
| Database           |
+--------------------+
| information_schema |
| books              |
| mysql              |
| performance_schema |
| test               |
+--------------------+

如图:




附图:



# -*- coding: utf-8 -*-
"""
Spyder Editor




This is a temporary script file.
"""
import pymysql




class MysqlDr(object):
    cnx = pymysql.connect(
                host = 'localhost',
                port = 3316,
                user = 'root',
                password = 'root',
                database = 'test',
                charset = 'utf8'
            )
conn = MysqlDr.cnx
cur = conn.cursor()
cur.execute('select version()')
data = cur.fetchone()
print('mysql version:%s' %data)




cur.execute('show databases;')
databases = cur.fetchall()




s = '''
+--------------------+
| Database           |
+--------------------+
'''
print(s,end='')
compare = 0
#print(type(databases))
for i in range(len(databases)):
    #print(type(databases[i]))
    for j in range(len(databases[i])):
        #print('| ',databases[i][j].ljust(20),'|')
        #print(len(databases[i][j]))
        if(compare <= int(len(databases[i][j]))):
            compare = int(len(databases[i][j]))
        else:
            pass
        #print(compare)
        if(i+j == len(databases)-1):
        print('|',databases[i][j].ljust(compare),'|',end='')
        else:
        print('|',databases[i][j].ljust(compare),'|')


end = '''
+--------------------+
'''
print(end)
conn.close()








阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页