Python学习笔记(二)

Mysql连接

config={
    'host' : '127.0.0.1',
    'database' : 'dbname',
    'user' : '',
    'password' : '',
    'charset' : 'utf8',
    'port' : 3306,
    #'_connection_string' : "mysql:host=127.0.0.1;dbname=dbname;port=3306"
    }
@staticmethod
    def get_user_info(dealer_id):
        db = config.DBConfig.get()
        try:
            cnn = mysql.connector.connect(**db)
            cursor = cnn.cursor()

            sql_query = """SELECT id,user_name,age,gender,score FROM user_tbl WHERE user_name like %s limit 10 """
            cursor.execute(sql_query,('nibushiren',))
        #打印列名
            column_names = cursor.column_names
            print("""{} {}	{}	{}""".format(*column_names))
            index = 0
            for id,user_name,age,gender in cursor:
                if index > 100:
                    break
                print('%4d		%10s		%2d	%2s	%6.4f' % (id,user_name,age,gender,score))
                index += 1
            cursor.close()
            cnn.close()
        except mysql.connector.Error as e:
            print('connect fails!{}'.format(e))

以上是读数据库操作。
未完待续。

原文地址:https://www.cnblogs.com/slankka/p/9158513.html