python connects to Mysql database

PyMySQL is a library for connecting to MySQL servers in Python 3.x, and mysqldb in Python 2.
PyMySQL follows the Python Database API v2.0 specification and includes the pure-Python MySQL client library.

 

PyMySQL installation

1. pip install
$ pip install PyMySQL

2. Use the git command to download the installation package and install (you can also download it manually):
$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install

######
The error message "ImportError: No module named setuptools" may appear during the installation, which means that you do not have setuptools installed. You can visit https://pypi.python.org/pypi/setuptools to find each system installation method.
Linux system installation example:
$ wget https://bootstrap.pypa.io/ez_setup.py
$ python3 ez_setup.py

 

Python connect MYSQL

Python operation database, basic steps

1. Import the corresponding python module
2. Use the connect function to connect to the database and return a connection object
3. Return a cursor object through the cursor method of the connection object
4. Execute the sql statement through the execute method of the cursor object
5. If the query is executed statement, obtain the return result through the fetchall statement of the
cursor object 6. Call the close method of the cursor object to close the cursor
7. Call the close method of the connection object to close the database connection

connect to mysql database

1. Create a test library
create table employee(
first_name char(10),
last_name char(10),
age int(10),
sex char(10),
income float
);

2. Create a remote connection authorization account
mysql> grant all on *.* to test@'%' identified by 'test123';
Query OK, 0 rows affected (0.14 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.03 sec)

3. Write the script

#!/usr/bin/python3

import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor() # 使用 cursor() 方法创建一个游标对象 cursor
cursor.execute("SELECT VERSION()") #使用 execute() 方法执行 SQL 查询
data = cursor.fetchone() # 使用 fetchone() 方法获取单条数据.
print("Database version :{0}".format(data))
#print("Database version: %s" % data)
db.close()

执行
python3 mysql_con.py
Database version :('5.6.40',)

 

创建数据库表
import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")
cursor = db.cursor()

cursor.execute("DROP TABLE IF EXISTS employee")
sql = """create table employee(
first_name char(10),
last_name char(10),
age int(10),
sex char(10),
income float)"""

cursor.execute(sql)
db.close()

 

数据库插入操作
import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")
cursor = db.cursor()

sql = """insert into employee(first_name,
last_name,age,sex,income)
values('rock','lin',20,'M',2000)"""

try:
    cursor.execute(sql)
    db.commit() #提交数据库执行
except:
    db.rollback() #如果发生错误则回滚

db.close()

 

数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
fetchall():接收全部的返回结果行.
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

实例:
import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")

cursor = db.cursor()
cursor.execute("select * from employee")
data = cursor.fetchall() #获取SQL语句所有记录
for user in data: #对返回的记录进行遍历
    print(user)
db.close()

执行
[root@vm80 db]# python3 mysql_con.py
('rock', 'lin', 20, 'M', 2000.0)
('su', 'tian', 18, 'F', 1000.0)

数据库更新操作
import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")
cursor = db.cursor()

sql = "UPDATE employee set age = age + 1 where sex = 'M'" #SQL更新操作

try:
   cursor.execute(sql)
   db.commit()
except:
    db.rollback()

db.close()

验证

mysql> select * from employee;
+------------+-----------+------+------+--------+
| first_name | last_name | age | sex | income |
+------------+-----------+------+------+--------+
| rock | lin | 21 | M | 2000 |

 

数据库删除操作
import pymysql

db = pymysql.connect("192.168.100.150","test","test123","testdb")
cursor = db.cursor()

sql = "delete from employee where age > 20" # SQL 删除语句

try:
    cursor.execute(sql)
   db.commit()
except:
   db.rollback()

db.close()


验证
mysql> select * from employee;
Empty set (0.00 sec)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325378358&siteId=291194637