Table of Contents
1. Background
2. Basic operations
1. Install the PyMySQL library
2. Install MySQL database
3. SQL basic syntax
4. Connect to the database
5. Add, delete, modify and query operations
3. Import big data files
Home Database Mysql Tutorial How to use Python to play with MySQL database

How to use Python to play with MySQL database

May 26, 2023 pm 02:46 PM
mysql python

1. Background

I conducted the connection experiment in Anaconda notebook, using the environment Python3.6. Of course, the operation can also be performed in the Python Shell.

The most commonly used and stable python library for connecting to MySQL database is PyMySQL.

2. Basic operations

1. Install the PyMySQL library

The simplest way:

Enter on the command linepip install pymysql

Or:

Download the whl file [1] for installation. The installation process is done by yourself.

2. Install MySQL database

There are two MySQL databases:

MySQL and MariaDB

I'm using MariaDB, which is a fork of MySQL.

The two are compatible in most aspects of performance, and you can’t feel any difference when using them.

gives the download address: MySQL[2], MariaDB[3], the installation process is very simple, just follow Next Step, but remember the password.

There is a small episode. MySQL and MariaDB are equivalent to the relationship between sisters and sisters. They were created by the same person (Widenius).

After MySQL was acquired by Oracle, Mr. Widenius felt unhappy, so he built MariaDB, which can completely replace MySQL.

Daniel is willful.

3. SQL basic syntax

Next, we will use SQL table creation, query, data insertion and other functions. Here is a brief introduction to the basic statements of SQL language.

  • View database: SHOW DATABASES;

  • Create database: CREATE DATEBASE database name;

  • Use database: USE database name;

  • View data table:SHOW TABLES;

  • Create data table: CREATE TABLE table name (column name 1 (data type 1), column name 2 (data type 2));

  • Insert data: INSERT INTO table name (column name 1, column name 2) VALUES (data 1, data 2);

  • View data: SELECT * FROM table name;

  • Update data: UPDATE table name SET column name 1 = new data 1, column name 2 = New data 2 WHERE A certain column = a certain data;

4. Connect to the database

After installing the necessary files and libraries, officially start connecting to the database Well, it’s mysterious but not difficult!

#首先导入PyMySQL库
import pymysql
#连接数据库,创建连接对象connection
#连接对象作用是:连接数据库、发送数据库信息、处理回滚操作(查询中断时,数据库回到最初状态)、创建新的光标对象
connection = pymysql.connect(host = 'localhost' #host属性
                            user = 'root' #用户名
                            password = '******'  #此处填登录数据库的密码
                            db = 'mysql' #数据库名
                            )
Copy after login

Execute this code and the connection will be completed!

5. Add, delete, modify and query operations

First check which databases there are:

#创建光标对象,一个连接可以有很多光标,一个光标跟踪一种数据状态。
#光标对象作用是:、创建、删除、写入、查询等等
cur = connection.cursor()
#查看有哪些数据库,通过cur.fetchall()获取查询所有结果
print(cur.fetchall())
Copy after login

Print out all databases:

(('information_schema',),
('law',),
('mysql',),
('performance_schema',),
('test',))
Copy after login

Create in the test database Table:

#使用数据库test
cur.execute('USE test')
#在test数据库里创建表student,有name列和age列
cur.execute('CREATE TABLE student(name VARCHAR(20),age TINYINT(3))')
Copy after login

Insert a piece of data into the data table student:

sql = 'INSERT INTO student (name,age) VALUES (%s,%s)'
cur.execute(sql,('XiaoMing',23))
Copy after login

View the content of the data table student:

cur.execute('SELECT * FROM student')
print(cur.fetchone())
Copy after login

The printout is: ('XiaoMing', 23)

Bingo! It’s a piece of data we just inserted

Finally, remember to close the cursor and connection:

#关闭连接对象,否则会导致连接泄漏,消耗数据库资源
connection.close()
#关闭光标
cur.close()
Copy after login

OK, the whole process is roughly like this.

Of course, these are very basic operations. More usage methods need to be found in the PyMySQL official documentation [4].

3. Import big data files

Take csv files as an example. There are generally two methods for importing csv files into the database:

1. Import one by one through the insert method of SQL , suitable for CSV files with small data volume, and will not be described in detail here.

2. Importing through the load data method is fast and suitable for big data files, which is also the focus of this article.

The sample CSV file is as follows:

How to use Python to play with MySQL database

The overall work is divided into 3 steps:

1. Use python to connect to the mysql database;

2、基于CSV文件表格字段创建表;

3、使用load data方法导入CSV文件内容。

sql的load data语法简介:

LOAD DATA LOCAL INFILE 'csv_file_path' INTO TABLE table_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES
Copy after login

csv_file_path 指文件绝对路径 table_name指表名称 FIELDS TERMINATED BY ','指以逗号分隔 LINES TERMINATED BY '\\r\\n'指换行 IGNORE 1 LINES指跳过第一行,因为第一行是表的字段名

下面给出全部代码:

#导入pymysql方法
import pymysql


#连接数据库
config = {:'',
         :3306,
         :'username',
         :'password',
         :'utf8mb4',
         :1
         }
conn = pymysql.connect(**config)
cur = conn.cursor()


#load_csv函数,参数分别为csv文件路径,表名称,数据库名称
def load_csv(csv_file_path,table_name,database='evdata'):
   #打开csv文件
   file = open(csv_file_path, 'r',encoding='utf-8')
   #读取csv文件第一行字段名,创建表
   reader = file.readline()
   b = reader.split(',')
   colum = ''
   for a in b:
       colum = colum + a + ' varchar(255),'
   colum = colum[:-1]
   #编写sql,create_sql负责创建表,data_sql负责导入数据
   create_sql = 'create table if not exists ' + table_name + ' ' + '(' + colum + ')' + ' DEFAULT CHARSET=utf8'
   data_sql = "LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES" % (csv_filename,table_name)

   #使用数据库
   cur.execute('use %s' % database)
   #设置编码格式
   cur.execute('SET NAMES utf8;')
   cur.execute('SET character_set_connection=utf8;')
   #执行create_sql,创建表
   cur.execute(create_sql)
   #执行data_sql,导入数据
   cur.execute(data_sql)
   conn.commit()
   #关闭连接
   conn.close()
   cur.close()
Copy after login

The above is the detailed content of How to use Python to play with MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Does Python projects need to be layered? Does Python projects need to be layered? Apr 19, 2025 pm 10:06 PM

Discussion on Hierarchical Structure in Python Projects In the process of learning Python, many beginners will come into contact with some open source projects, especially projects using the Django framework...

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

See all articles