Advanced Python ----- operate mysql database

Table of contents

Foreword:

Install pymysql

Test connection database

import module

Test connection query operation

Return results fecthone, fecthmany, fecthall

Create and manage databases

Table creation and CRUD

1. Create a table

 2. View the table structure

 3. View all tables

4. Delete table

5. Object-oriented writing 


Foreword:

        After learning the basic statements of MySQL earlier, some people will ask, how to operate the mysql database through the programming language? This can’t be done only with sql commands, right? The answer is that it can be operated through a programming language, but the sql command is the basic command to operate the database, and the programming language is only an auxiliary function to combine the database with other programs. Then in this issue, I will explain how to connect to the MySQL database through Python, and at the same time realize database and other related operations

Install pymysql

what is pymysql 

pymysql is a third-party module for operating databases in Python. Through the related methods of this module, we can connect and operate mysql databases.

Install

Enter cmd, then enter pip install pymysql

 Wait for a while and it will be installed, then enter pip list  to check whether it is installed, as shown in the figure (indicating that it has been installed):

Well, after the installation is complete, start writing code.

Test connection database

import module

import pymysql as psql

Test connection query operation

import pymysql as psql
#连接数据库
db=psql.connect(
    host='localhost', #这里是表示数据库地址
    user='heweijie',    #这里是表示用户名
    password='heweijie',    #这里是表示password
    database='hello',   #这里是表示要连接的数据库名字
    charset='utf8'      #这里是字符编码,一般都选utf8
)

#创建读取游标
cur=db.cursor()
sql=r'select version();' #sql语句,查看mysql版本

cur.execute(sql)      #执行sql语句
data=cur.fetchone()   #返回一条信息

print(data)

cur.close()     #关闭游标
db.close()      #关闭数据库的连接

#输出结果:('8.0.30',)

Here we can see that we have successfully connected to the database and returned a result at the same time. It should be noted that when we end using the database, we must remember to close the connection to the database, so as not to cause problems such as data leakage of the database.

connect() method parameters

parameter illustrate
host= Database connection address
user= database username
password= database password
database= The name of the database to connect to
port=3306 Connection port, generally play 3306
charset=utf8 Set the character set, usually utf8
connect_timeout=10 The connection database timeout time, generally defaults to 10 seconds
dsn Data source name, given this parameter indicates database dependency

Return results fecthone, fecthmany, fecthall

 When we execute the sql query command, we need to obtain the returned result, but the returned result can be a single line, multiple custom lines, or return all the results. To achieve this effect, we need The three methods of fecthone, fecthmany, and fecthall are used. Look at the example below

 Current database table information:


#创建读取游标
cur=db.cursor()
sql=r'select *from user' #sql语句,查看mysql版本
cur.execute(sql)      #执行sql语句

#返回一条信息
data1=cur.fetchone()
print('fecthone>>>',data1)

#返回自定义条数
data2=cur.fetchmany(5)
print('fetchmany>>>',data2)

#返回全部信息
data3=cur.fetchall()
print('fecthall>>>',data3)

 At this time, you will find a phenomenon. Every time you return the information, when you get the information again, you will not return this information, but continue to read. This is the same as reading a text file. The cursor cur reads downwards, so the information obtained earlier will not be returned. If you want to return the previous information, you can re-create the cursor, execute the new command and it will be OK.

Create and manage databases

        The sql command is the basic command to operate the database, and the programming language plays an auxiliary role, so the real operation of the database is the sql command, and we only process the obtained information through the programming language. Here's how to create a database through Python

import pymysql as psql
class Database:
    '''通过面对对象的方式去创建一个数据库以及
    实现数据库管理操作方法'''
    def __init__(self):
        self.db=psql.connect(
            host='localhost',
            user='heweijie',
            password='heweijie',
            charset='utf8'
        )
        #操作游标
        self.cur = self.db.cursor()
    def create(self,name):
        '''创建一个数据库,名字为name,自行输入'''
        try:
            sql=fr'create database if not exists {name}'
            self.cur.execute(sql)
        except Exception as e:
            print(e)
            print('创建失败')
            self.db.rollback() #事物的回滚操作,就是回到开始
    def showdatabases(self):
        '''查看全部数据库名字'''
        sql=r'show databases'
        self.cur.execute(sql)
        result=self.cur.fetchall()
        return result
    #删除数据库
    def dropdatabase(self,name):
        try:
            sql=fr'drop database {name}'
            self.cur.execute(sql)
        except Exception as e:
            print(e)
            print('删除失败')
            self.db.rollback()

    def close(self):
        '''关闭连接,结束操作'''
        self.cur.close()
        self.db.close()
#操作示例:
if __name__ == '__main__':  
    d=Database()
    d.create('fucc')
    print(d.showdatabases())
    d.dropdatabase('fucc')
    print(d.showdatabases())
    d.close()

Table creation and CRUD

        The table is the storage container in the database, and the data is basically stored in the table. Next, create a table operation object to operate on the data in the table.

1. Create a table

To create a table, you must first connect to the database, obtain the current database db, and then enter the sql command to create the table. The sql command: create table if not exists table name (...table structure...);

def connect(database_name):
    db = psql.connect(
        host='127.0.0.1',
        user='heweijie',
        password='heweijie',
        port=3306,
        database=database_name,
        charset='utf8'
    )
    return db #返回当前连接的数据库
def createtable(name):
    db=connect('test') #数据库名字为test
    cur=db.cursor()
    try:
        sql=f'create table if not exists {name}(id int primary key auto_increment,name char(50),num int);'
        print('创建成功')
    except Exception as e:
        print(e)
        db.rollback()

 2. View the table structure

The sql command is: desc table name;

#………………
def desctable(name): #表的名字为name
    db=connect('test')
    cur=db.cursor()
    sql=f'desc {name}'
    cur.execute(sql)
    print(cur.fetchall()) #输出全部结果

 3. View all tables

sql command: show tables;

#…………
def showtables():
    db=connect('test')
    cur=db.cursor()
    sql='show tables;'
    cur.execute(sql)
    print(cur.fetchall())

4. Delete table

sql command: drop table table name;

#………………
def droptable(name):
    db = connect('test')
    cur = db.cursor()
    try:
        sql = f'drop table {name};'
        cur.execute(sql)
        print('删除成功')
    except Exception as e:
        print(e)
        db.rollback()

5. Object-oriented writing 

#创建表以及操作
class Table(object):
    def __init__(self,database_name):
        '''连接数据库database_name,自写'''
        self.db=psql.connect(
            host='127.0.0.1',
            user='heweijie',
            password='heweijie',
            port=3306,
            database=database_name,
            charset='utf8'
        )
        self.cur=self.db.cursor()
    def create(self,sql):
        '''创建表,sql语句自行写入'''
        try:
            self.cur.execute(sql)
            print('create successfully')
        except Exception as e:
            print(e)
            self.db.rollback()
    def desctable(self,table):
        '''查看表结构'''
        sql=fr'desc {table};'
        self.cur.execute(sql)
        result=self.cur.fetchall()
        print(result)
    def showtables(self):
        '''查看这个数据库里面的全部表'''
        sql=f'show tables;'
        self.cur.execute(sql)
        result=self.cur.fetchall()
        print(result)
    def droptable(self,name):
        '''把名字为name的表删除'''
        try:
            sql=f'drop table {name};'
            self.cur.execute(sql)
        except Exception as e:
            print(e)
            self.db.rollback()
    def insert(self,sql):
        '''插入数据,sql语句自写'''
        try:
            self.cur.execute(sql)
        except Exception as e:
            print(e)
            self.db.rollback()
    def selectdata(self,sql):
        '''查询数据,sql语句自写'''
        self.cur.execute(sql)
        result=self.cur.fetchall()
        print(result)
#使用示例
if __name__ == '__main__':
    user=Table('hello')
    user.create(r'create table if not exists mydatabase (id int primary key auto_increment,name char(50),num int);')
    user.showtables()
    user.desctable('mydatabase')
    user.selectdata('select *from user;')#user 是另外一个表
    user.droptable('mydatabase')
    user.showtables()

The above is the content of today, see you in the next issue!

 Share a wallpaper:

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/129642834