一、模块导入 
 
二、创建连接对象 1 2 3 4 5 6 7 8 9 10 11 12 13 14 conn = pymysql.connect( host = 'localhost' ,                         port = 3306 ,                         user = 'root' ,                         password = 'root' ,                         database = 'mysql' ,                         charset = 'utf8' ) 
 
连接对象相关操作 
关闭连接:conn.close() 
提交数据:conn.commit() 
撤销数据:conn.rollback() 
将修改操作提交到数据库:conn.commit()  
回滚数据:conn.rollback()  
 
三、获取游标对象 目的:执行sql语句,完成对数据库的增、删、改、查操作
 
游标相关操作 
执行sql语句,并返回受影响的行数:cur.execute()  
获取查询结果集中的一条数据,返回一个元组:cur.fetchone() 
获取查询结果集中的所有数据,返回一个元组:cur.fetchall() 
关闭游标:cur.close() 
 
四、数据操作 1. 查询数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import  pymysqlconn = pymysql.connect( host = 'localhost' ,                         port = 3306 ,                         user = 'root' ,                         password = 'root' ,                         database = 'mysql' ,                         charset = 'utf8' ) cursor = conn.cursor() sql = 'select * from info;'  row_count = cursor.execute(sql) print ('SQL语句执行影响的行数:%d'  % row_count)print (cursor.fetchone())for  line in  cursor.fetchall():    print (line) cursor.close() conn.close() 
 
2. 修改数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import  pymysqlconn = pymysql.connect( host = 'localhost' ,                         port = 3306 ,                         user = 'root' ,                         password = 'root' ,                         database = 'mysql' ,                         charset = 'utf8' ) cursor = conn.cursor() try :                             sql = "update info set short = '全新好' where id = 1"           row_count = cursor.execute(sql)     print ('SQL语句执行影响的行数:%d'  % row_count)          conn.commit() except  Exception as  e:    print (e)          conn.rollback() cursor.close() conn.close() 
 
五、防止SQL注入 
SQL注入:用户通过字符串拼接影响SQL语句的语义,提交带有恶意的数据的SQL语句,最终产生数据泄露的现象 
防止SQL注入:SQL语句参数化,参数使用%s来占位,将%s占位所需要的参数存在一个列表中,把参数列表传递给execute方法中第二个参数(execute方法中的 %s 占位不需要带引号) 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 from  pymysql import  connectdef  main ():    find_name = input ("请输入物品名称:" )          conn = connect(host='localhost' ,port=3306 ,user='root' ,password='mysql' ,database='jing_dong' ,charset='utf8' )          cs1 = conn.cursor()                                                  params = [find_name]          count = cs1.execute("select * from goods where name=%s" , params)                              print (count)               result = cs1.fetchall()          print (result)          cs1.close()          conn.close() if  __name__ == '__main__' :    main() 
 
附录-参考资料 PyMSQL官方文档 https://pymysql.readthedocs.io/en/latest/modules/connections.html