mac uses python to operate mysql

mac installation mysql reference (2023) mac installation mysql_Vermouth_00's blog - CSDN blog

Recently, I am looking at the database and trying to use python to operate mysql. First, I need to install mysql on the computer, then install the pymysql library in python, use pycharm to connect to mysql, create a database and table and insert data, and finally I can use python to add, delete, modify and query the database.

1. Install the driver

Common mysql libraries for python are:

MySQLdb(mysqlclient),mysql-connector-python,pymysql

The difference between MySQLdb and mysqlclient:

         MySQLdb only supports python 2.x version, mysqlclient is a branch of MySQLdb, which solves the compatibility problem of python 3.x.

mysqlclient

        1) It is a C extension module, compiling and installing may cause various errors to be reported, obviously not as convenient as pymysql;

        2) Fast speed;

pymysql

        1) Implemented in pure Python, easy to install (direct pip installation);

        2) Since it is implemented in pure Python, it can be well combined with the gevent framework;

mysql-connector-python is also pure python, which is the official driver of msql. The efficiency and portability of pymysql are theoretically similar to those of mysql-connector-python.

In summary, choose pymysql.

Install pymysql

Terminal run pip3 install pymysql3

If you are prompted: Operation not permitted, add sudo in front of the command to indicate that the administrator has permission to run this command.

There is no error in import pymysql in pycharm, indicating that the installation is successful.

Two, pycharm connects to mysql

 Open the database on the right side of pycharm, click the + sign to add a database, and select mysql;

In the dialog box that pops up, there are several items that need to be filled in: user, password, database. If the driver is not installed as shown below, you need to download the driver, and finally you can test whether the connection is successful.

a. User: Mysql的username

b. Password: Mysql的password

c. Database: database name

d. Automatically download missing drivers

e. Test connection: Test whether the connection is successful

It should be noted that the user name is the user of the database, the user name and password must be correct, the user needs to have remote access authority, the background mysql service needs to be started normally, port 3306 is not occupied, the version of mysql driver must match the version of mysql installed on the computer, and the test connection can only succeed if these conditions are met. 

If the test connection reports an error here, you can refer to this article to troubleshoot the problem: The pit encountered by Pycharm connecting to mysql, the error Access denied for user 'root'_Vermouth_00's Blog-CSDN Blog

After the test connection is successful, click apply, and then click ok.

3. Create database and tables

1. Create a database

create database StudentSystem;

show databases;

2. Create a table

use StudentSystem;

CREATE TABLE test_student (

id int(10) unsigned NOT NULL AUTO_INCREMENT,

name varchar(20) DEFAULT NULL,

description varchar(20) DEFAULT NULL,

sex varchar(2) DEFAULT NULL,

PRIMARY KEY (id)

) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

这里遇到报错ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(20) DEFAULT NULL,sex varchar(2) DEFAULT NULL,PRIMARY KEY (id)' at line 4

The error is reported because desc is a keyword, just replace it with description;

Execute again, passed, but there are warnings

show warnings;

view warnings

Since MySQL 8.0.17, it is not recommended to specify the display width for int, and this rule will be deleted in future versions.

Currently an alias for the charset utf8mb3, but will be an alias for utf8mb4 in a future release. Consider using utf8mb4 so that it is not ambiguous.

The utf8 in MySQL is utf8mb3, which is compatible with three-byte unicode characters at most. MySQL has added utf8mb4 encoding after version 5.5.3, and mb4 means most bytes 4, which is specially used to be compatible with four-byte unicode characters .

show tables;

3. Insert data

INSERT INTO table name (field 1, field 2, ...) VALUES (value 1, value 2, ...);

insert into test_student values( 1120233310 , '小何' , '软件工程' , '女' );

insert into test_student values( 1120232394 , '小张' , '计算机科学与技术' , '男' );

insert into test_student values( 1120232764 , '姚姚' , '物联网' , '女' );

Fourth, python operates the database

execute only accepts a sql string as a parameter

  • If execute is an addition, deletion or modification operation, it returns the number of affected rows

  • execute is a query operation, returning the total number of data found

A cursor is a mechanism for traversing data in the database, which allows us to execute queries in the database and traverse the result set.

(1) Query operation

import pymysql

#连接数据库
conn = pymysql.connect(
    host='localhost',
    user='test',
    password='hejiahuan04',
    database='StudentSystem'
)
#创建游标对象:cursor
cursor = conn.cursor()

#查询语句
sql = 'select * from test_student'
#执行
cursor.execute(sql)
# 获得全部结果
result = cursor.fetchall()
print(result)
# #另一种方式
# result = cursor.execute(sql)
# for i in range(result):
#     print(cursor.fetchone())
#result可以返回我们操作的行数。fetchone()可以返回记录,一条一条输出。

# 关闭连接
cursor.close()
conn.close()

 data = cursor.fetchall() # data is an iterable object, the value inside can be obtained by traversing, data is a tuple, and the elements of the tuple are also sub-tuples one by one.

(2) Insert operation

Except for the query operation that does not need to write conn.commit(), other operations need to be written, otherwise it cannot be completed.

def insert_sql():
    #插入
    sql_insert = "insert into test_student values (1120231126,'飞飞','土木工程','女')"
    cursor.execute(sql_insert)
    conn.commit()

(3) Delete operation

def delete_sql():
    #删除
    sql_delete = "delete from test_student where name='飞飞'"
    cursor.execute(sql_delete)
    conn.commit()

(4) Update operation

def update_sql():
    #更新,把飞飞的性别改成男
    sql_update = "update test_student set sex='男' where name='飞飞'"
    cursor.execute(sql_update)
    conn.commit()

(5) Batch insertion

executemany can be used to perform batch inserts.

def insert_many():
    #批量插入
    # SQL 插入语句
    sql_insert_many = "insert into test_student(id,name,description,sex) values (%s,%s,%s,%s)"
    # 一个tuple或者list
    T = ((1120230039, '小李', '国贸', '男'),(1120230520, '小王', '数据分析', '女'),(1120231202, '小陈', '法律', '女'))
    try:
        cursor.executemany(sql_insert_many,T)
        conn.commit()
    except:
        # 如果发生错误则回滚
        conn.rollback()

Guess you like

Origin blog.csdn.net/Vermouth_00/article/details/131008234