Python3 连接和操作数据库

2019-11-02  本文已影响0人  Queenie的学习笔记

1. 连接数据库

#coding:utf-8
import mysql.connector  #python2使用的是import MySQLdb.cursors

class OperationMysql:
    def __init__(self):     
        self.conn = mysql.connector.connect(
                host='xxx.xxx.xxx.xxx',
                port=3306,
                user='???',
                passwd='???',
                db='???',
                charset='utf8'
                )
        self.cur = self.conn.cursor(dictionary=True)    #传递dictionary,返回dict类型

    def search_one(self,sql):
        self.cur.execute(sql)
        result = self.cur.fetchone()
        return result

2. 操作数据库

if __name__ == '__main__':
    op_mysql = OperationMysql()
    result1 = op_mysql.search_one("select * from xt_yhzh where zhmc='Zhaowenjun'")
    print(result1)

3. 结果

传递dictionary的结果 不传递dictionary的结果
上一篇 下一篇

猜你喜欢

热点阅读