Article Directory
PyMySQL use
learning target
- PyMySQL database can be used to complete the CRUD
1. Thoughts
How to insert 100,000 data to the MySQL database?
answer:
If you use this operation to complete the study before the MySQL client, then the workload will be enormous, we can go to connect to the MySQL database through the use of program code, and then the MySQL database CRUD way to achieve data 10000 insertion like manner using code called a database database programming.
2. Python program operations MySQL database
Pymysql install third-party packages:
sudo pip3 install pymysql
Description:
- Installation command sudo pip3 install a third-party package name
- Uninstall command using sudo pip3 uninstall third-party packages
- : We now use a third-party virtual machines already have this package installed, you can use pip3 show pymysql information command to view the third-party packages
- pip3 list to view the list of packages using the command to install the third-party pip
pymysql use:
-
Import module pymysql
import pymysql
-
Create a connection object
Pymysql module calls connect () function to create a connection object, as follows:
conn=connect(参数列表) * 参数host:连接的mysql主机,如果本机是'localhost' * 参数port:连接的mysql主机的端口,默认是3306 * 参数user:连接的用户名 * 参数password:连接的密码 * 参数database:数据库的名称 * 参数charset:通信采用的编码方式,推荐使用utf8
Instructions connection object:
- Close the connection conn.Close ()
- Submit data conn.commit ()
- Revocation data conn.rollback ()
-
Gets cursor object
Get a cursor object's goal is to be executed sql statement, completed by the database, delete, change, check operation. code show as below:
# 调用连接对象的cursor()方法获取游标对象 cur =conn.cursor()
Cursor Instructions:
- Use a cursor to execute SQL statements: execute (operation [parameters]) to execute SQL statements, returns the number of rows affected, mainly used to perform insert, update, delete, select other statements
- Obtaining a query result set of data: cur.fetchone () returns a tuple, such as (1, 'John Doe')
- Get all the data query result set: cur.fetchall () returns a tuple, such as ((1, 'John Doe'), (2, 'John Doe'))
- Close the cursor: cur.close (), indicates the completion of database operations, and
-
pymysql complete query data
import pymysql # 创建连接对象 conn = pymysql.connect(host='localhost', port=3306, user='root', password='mysql',database='python', charset='utf8') # 获取游标对象 cursor = conn.cursor() # 查询 SQL 语句 sql = "select * from students;" # 执行 SQL 语句 返回值就是 SQL 语句在执行过程中影响的行数 row_count = cursor.execute(sql) print("SQL 语句执行影响的行数%d" % row_count) # 取出结果集中一行数据, 例如:(1, '张三') # print(cursor.fetchone()) # 取出结果集中的所有数据, 例如:((1, '张三'), (2, '李四'), (3, '王五')) for line in cursor.fetchall(): print(line) # 关闭游标 cursor.close() # 关闭连接 conn.close()
-
pymysql completed additions and deletions to the data
import pymysql # 创建连接对象 conn = pymysql.connect(host='localhost', port=3306, user='root', password='mysql',database='python', charset='utf8') # 获取游标对象 cursor = conn.cursor() try: # 添加 SQL 语句 # sql = "insert into students(name) values('刘璐'), ('王美丽');" # 删除 SQ L语句 # sql = "delete from students where id = 5;" # 修改 SQL 语句 sql = "update students set name = '王铁蛋' where id = 6;" # 执行 SQL 语句 row_count = cursor.execute(sql) print("SQL 语句执行影响的行数%d" % row_count) # 提交数据到数据库 conn.commit() except Exception as e: # 回滚数据, 即撤销刚刚的SQL语句操作 conn.rollback() # 关闭游标 cursor.close() # 关闭连接 conn.close()
Description:
- conn.commit () shows a modification operation submitted to the database
- conn.rollback () indicates data rollback
-
Prevent SQL injection
What is SQL injection?
SQL statements and data submitted by the user with a malicious way of stitching string, thus affecting the semantics of SQL statements, and ultimately generate data leakage phenomenon.
How to prevent SQL injection?
Parameterized SQL statements
- % S SQL parameters to placeholder language string formatting operations described herein are not in python
- The parameters of the SQL statement required to% s placeholder is present in a list, the parameter list passed to execute a second process parameter
Sample code to prevent SQL injections:
from pymysql import connect def main(): find_name = input("请输入物品名称:") # 创建Connection连接 conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8') # 获得Cursor对象 cs1 = conn.cursor() # 非安全的方式 # 输入 ' or 1 = 1 or ' (单引号也要输入) # sql = "select * from goods where name='%s'" % find_name # print("""sql===>%s<====""" % sql) # # 执行select语句,并返回受影响的行数:查询所有数据 # count = cs1.execute(sql) # 安全的方式 # 构造参数列表 params = [find_name] # 执行select语句,并返回受影响的行数:查询所有数据 count = cs1.execute("select * from goods where name=%s", params) # 注意: # 如果要是有多个参数,需要进行参数化 # 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可 # %s 不需要带引号 # 打印受影响的行数 print(count) # 获取查询的结果 # result = cs1.fetchone() result = cs1.fetchall() # 打印查询的结果 print(result) # 关闭Cursor对象 cs1.close() # 关闭Connection对象 conn.close() if __name__ == '__main__': main()
Description:
- The execute method does not require the quotation marks% s placeholder
3. Summary
-
Guide package
import pymysql
-
Create a connection object
pymysql.connect(参数列表)
-
Gets cursor object
cursor =conn.cursor()
-
Execute SQL statements
row_count = cursor.execute(sql)
-
Acquiring a query result set
result = cursor.fetchall()
-
The modification operation submitted to the database
conn.commit()
-
Rollback data
conn.rollback()
-
Close the cursor
cursor.close()
-
Close the connection
conn.close()