search
HomeBackend DevelopmentPython TutorialIntroduction to the basic knowledge of Mysql database programming in python learning

In Python web crawlers, it is usually stored in TXT plain text, but it can also be stored in a database; at the same time, in WAMP (Windows, Apache, MySQL, PHP or Python) development websites, it can also be built through Python Web page, so this article mainly talks about the programming knowledge related to Python calling MySQL database

In Python web crawler, it is usually stored in TXT plain text, but it can also be stored in the database; at the same time, in WAMP ( Windows, Apache, MySQL, PHP or Python) can also build web pages through Python, so this article mainly talks about programming knowledge related to Python calling MySQL database. Explain from the following aspects:

1. Configuring MySLQ
2. Basic knowledge of SQL statements
3. Basic knowledge of Python operating MySQL
4. Python calling MySQL example

1. Configure MySQL

                                                                                                                                                                                                                         First download mysql-5.0.96-winx64, the installation process is as shown in the figure below.
1. Install MySQL 5.0

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning
2. Select Manual Configuration, Service Type, Universal Multi-Function and Installation Path

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning
3. Set the number of database access connections to 15 and the port to 3306 (used to set the URL in the code) , the encoding method is utf-8

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning
4. Set the user name and password of the default super root user, and finally the installation is successful

Introduction to the basic knowledge of Mysql database programming in python learningIntroduction to the basic knowledge of Mysql database programming in python learning

2. Basic knowledge of SQL statements

After successfully installing MySQL 5.0, perform simple operations on the database.
1. Run MySQL and enter the default user password 123456

Introduction to the basic knowledge of Mysql database programming in python learning

## 2. Create database test01 and use the database (use database directly for the second call)
create database test01;

Introduction to the basic knowledge of Mysql database programming in python learning

Display the databases contained in the database: show databases;

Introduction to the basic knowledge of Mysql database programming in python learning

## 3. Create Table student, in which student number is the primary key

Create table student(username varchar(20),password varchar(20),stuid int primary key);



Introduction to the basic knowledge of Mysql database programming in python learning

4. Display the table structure and use the statement desc student


Introduction to the basic knowledge of Mysql database programming in python learning
## 5. Report to Insert data into the student table and display the queried data


Introduction to the basic knowledge of Mysql database programming in python learning
6. Delete the table: drop table student;



Introduction to the basic knowledge of Mysql database programming in python learning 7. Update data

update student set password='000000' where stuid='1';




8. Delete dataIntroduction to the basic knowledge of Mysql database programming in python learning Delete from student where username='eastmount;



# At this point, the basic explanation of MySQL database operation is over, you can also implement the database For operations such as additions, deletions, modifications, queries, transactions, and stored procedures, it is recommended to install visual software to replace the black box, or use Navicat for MySQL software. The code is as follows:

Introduction to the basic knowledge of Mysql database programming in python learning

Enter password: ******
mysql> show databases;
+--------------------+
| Database      |
+--------------------+
| information_schema |
| mysql       |
| performance_schema |
| test        |
| test01       |
+--------------------+
5 rows in set (0.00 sec)

mysql> use test01;
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> create table student(username varchar(20),
  ->         password varchar(20),
  ->         stuid int primary key);
Query OK, 0 rows affected (0.33 sec)

mysql> show tables;
+------------------+
| Tables_in_test01 |
+------------------+
| student     |
+------------------+
1 row in set (0.00 sec)

mysql> desc student;
+----------+-------------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) | YES |   | NULL  |    |
| password | varchar(20) | YES |   | NULL  |    |
| stuid  | int(11)   | NO  | PRI | NULL  |    |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.03 sec)

mysql> insert student(username, password, stuid)
  -> values('eastmount','123456',1)
  -> ;
Query OK, 1 row affected (0.05 sec)

mysql> select * from student;
+-----------+----------+-------+
| username | password | stuid |
+-----------+----------+-------+
| eastmount | 123456  |   1 |
+-----------+----------+-------+
1 row in set (0.00 sec)

mysql> update student set password='000000' where stuid='1';
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from student;
+-----------+----------+-------+
| username | password | stuid |
+-----------+----------+-------+
| eastmount | 000000  |   1 |
+-----------+----------+-------+
1 row in set (0.00 sec)

mysql> delete from student where username='eastmount';
Query OK, 1 row affected (0.08 sec)

mysql> select * from student;
Empty set (0.00 sec)

mysql>

3. Basic knowledge of Python calling MySQL

The usual installation method is to use: pip install mysql installs Python's MySQL library, but an error always occurs. Common errors such as: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory

These may be driver issues.




Correct installation method:

It is recommended to download a MySQL-python-1.2.3.win-amd64-py2.7.exe file for installation. Introduction to the basic knowledge of Mysql database programming in python learningOfficial website address: https://pypi.python.org/pypi/MySQL-python/




下面我们要详细了解Python数据库API。从Python中访问数据库需要接口程序,接口程序是一个Python模块,它提供数据库客户端库(通常是C语言写成的)的接口供你访问。注意:Python接口程序都一定要遵守Python DB-API规范。
DB-API是一个规范。它定义了一系列必须的对象和数据库存取方式,以便为各种各样的底层数据库系统和多种多样的数据库接口程序提供一致的访问接口。DB-API为不同的数据库提供了一致的访问接口,在不同的数据库之间移植代码成为一件轻松的事情。

下面简单介绍DB-API的使用方法。

1.模块属性
DB-API规范里的以下特性和属性必须提供。一个DB-API兼容模块定义如下所示:

apilevel:模块兼容的DB-API版本号
threadsafety:线程安全级别
paramstyle:支持sql语句参数风格
connect():连接数据库

Python调用MsSQL需要导入MySQLdb库,如下:

import MySQLdb

 2.connect()函数

其中主要使用的方法是connect对象。connect()方法生成一个connect对象,用于访问数据库,其参数如下:

user:Username
password:Password
host:Hostname
database:DatabaseName
dsn:Data source name

注意并非所有的接口程序都严格按照这种格式,如MySQLdb。

import MySQLdb
conn = MySQLdb.connect(host='localhost', db='test01', user='root', passwd='123456', port=3306, charset='utf8')

connect()对象方法如下:

close():关闭数据库连接,或者关闭游标对象
commit():提交当前事务
rollback():取消当前事务
cursor():创建游标或类游标对象
errorhandler(cxn,errcls,errval):作为已给游标的句柄

注意,执行close()方法则上述的连接对象方法不能再使用,否则发生异常。commit()、rollback()、cursor()或许更对于支持事务的数据库更有意义。
数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完整地执行,要么完全地不执行。 一旦你完成了数据库连接,关闭了游标对象,然后在执行commit()提交你的操作,然后关闭连接。

3.游标对象
上面说了connect()方法用于提供连接数据库的接口,如果要对数据库操作那么还需要使用游标对象。游标对象的属性和方法:

fetchone():可以看作fetch(取出) one(一个),也就是得到结果集的下一行(一行)。
fetchmany(size):可以看作fetch(取出)many(多个),这里的参数是界限,得到结果集的下几行(几行)
fetchall():顾名思义,取得所有。
execute(sql):执行数据库操作,参数为sql语句。
close():不需要游标时尽可能的关闭

下面通过简单的示例进行讲解。

四. Python调用MySQL示例

在前面数据库中我们创建了数据库“test01”和表“student”,同时插入了数据。那么,怎样通过Python来显示呢?
1.查询所有数据库
首先,我们查看本地数据库中所包含的数据库名称,通过“show databases”语句。

import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
  cur=conn.cursor()
  res = cur.execute('show databases')
  print res
  for data in cur.fetchall():
    print '%s' % data
  cur.close()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1])

其中通过链接数据库代码为:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
访问root超级用户,其密码为“123456”,端口为“3306”,其结果如下:

Introduction to the basic knowledge of Mysql database programming in python learning

如果不知道本地数据库的名称,可以通过该方法,先查询数据库中包含哪些数据库,然后再连接该数据库进行相关的操作。

2.查询表
下面介绍查询表student中数据,代码如下,代码的具体含义是通过connect()连接数据库,通过conn.cursor()定义游标,然后调用游标的excute(sql)执行数据库操作,此处为查询操作,再通过fetchall()函数获取所有数据。

# coding:utf-8 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01', charset='utf8')
  cur=conn.cursor()
  res = cur.execute('select * from student')
  print u'表中包含',res,u'条数据\n'
  print u'数据如下:(姓名 密码 序号)'
  for data in cur.fetchall():
    print '%s %s %s' % data
  cur.close()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1])

输出结果如图所示:

Introduction to the basic knowledge of Mysql database programming in python learning


        对应的MySQL中的结果是一致的,下图是对应的结果。

Introduction to the basic knowledge of Mysql database programming in python learning

 3.创建表
下面这段代码是创建一张教师表,主要是通过commit()提交数据。

# coding:utf-8 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01', charset='utf8')
  cur=conn.cursor()
  
  #查看表
  print u'插入前包含表:'
  cur.execute('show tables')
  for data in cur.fetchall():
    print '%s' % data

  #插入数据
  sql = '''create table teacher(id int not null primary key auto_increment,
                name char(30) not null,
                sex char(20) not null
     )'''
  cur.execute(sql)

  #查看表
  print u'\n插入后包含表:'
  cur.execute('show tables')
  for data in cur.fetchall():
    print '%s' % data
  cur.close()
  conn.commit()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1])

输出结果如下所示,插入教师表,包含字段:教师序号(id)、教师名称(name)、教师性别(sex)。

Introduction to the basic knowledge of Mysql database programming in python learning

插入数据也可以通过execute(sql)方法实现,如:
cur.execute("insert into student values( 'yxz', '111111', '10')")
但插入的新数据通常是通过变量进行赋值,而不是固定的,所以要对这条语句中的值做修改。我们可以做如下修改:

# coding:utf-8 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01')
  cur=conn.cursor()
  
  #插入数据
  sql = '''insert into student values(%s, %s, %s)'''
  cur.execute(sql, ('yxz','111111', '10'))

  #查看数据
  print u'\n插入数据:'
  cur.execute('select * from student')
  for data in cur.fetchall():
    print '%s %s %s' % data
  cur.close()
  conn.commit()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1])

输出结果如下所示:

>>> 
插入数据:
esatmount 123456 1
yangxiuzhang 123456 2
xiaoy 123456 3
yxz 111111 10
>>>

同样,对数据库的增删改插都可以进行,请读者自行阅读。
推荐资料:python使用mysql数据库 - 虫师
后面我会结合Python爬虫讲述,如何将爬取的内容存储在数据库中,如我CSDN的博客,爬取博客标题、发布时间、阅读量和评论数。

Introduction to the basic knowledge of Mysql database programming in python learning

MySQL数据库中结果如下图所示:

Introduction to the basic knowledge of Mysql database programming in python learning

最后希望文章对你有所帮助,如果文章中存在不足或错误的地方,还请海涵~还是那句话,挺享受现在的老师生活,不论科研、项目,还是教学,很充实,加油!

The above is the detailed content of Introduction to the basic knowledge of Mysql database programming in python learning. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 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.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!