pymysql模块常用操作
程序员文章站
2022-03-02 08:12:17
pymysql安装 ` pip install pymysql ` 链接数据库、执行sql、关闭连接 增删改查操作 插入数据 查找数据 ......
pymysql安装
pip install pymysql
链接数据库、执行sql、关闭连接
import pymysql user = input('请输入用户名请输入密码:').strip() pwd= input("请输入密码:").strip() # 建立连接 conn = pymysql.connect( host = '192.168.1.1', port = '3306', user = 'root', password = '123', db = 'mytestdb', charset = 'utf8', ) # 获取游标 cursor = conn.cursor() # 执行sql语句 # sql = 'select * from user_table where user="%s" and pwd=%s' % (user,pwd) 自己拼接sql语句有安全风险 # rows = cursor.excute(sql) sql = 'select * from user_table where user="%s" and pwd=%s' rows = cursor.excute(sql,(user,pwd)) cursor.close() conn.close() if rows: print("登录成功") else: print("登录失败")
增删改查操作
插入数据
import pymysql user = input('请输入用户名请输入密码:').strip() pwd= input("请输入密码:").strip() # 建立连接 conn = pymysql.connect( host = '192.168.1.1', port = '3306', user = 'root', password = '123', db = 'mytestdb', charset = 'utf8', ) # 获取游标 cursor = conn.cursor() sql = 'insert into user_table(user,pwd) values(%s,%s)' # 插入单个数据 rows1 = cursor.excute(sql,(user,pwd)) # 插入多个数据 rows2 = cursor.excutemany(sql,[(user,pwd),('aaa','123'),('bbb','123')]) # 查看插入之前的数据库数量 print(cursor.lastrowid) conn.commit() cursor.close() conn.close()
查找数据
import pymysql user = input('请输入用户名请输入密码:').strip() pwd= input("请输入密码:").strip() # 建立连接 conn = pymysql.connect( host = '192.168.1.1', port = '3306', user = 'root', password = '123', db = 'mytestdb', charset = 'utf8', ) # 获取游标 cursor = conn.cursor() sql = 'select * from user_table;' # 查询 rows = cursor.excte(sql) # 取单个数据 single_data = cursor.fetchone() # 取多个数据 multiple_data = cursor.fetchmany(2) # 取出所有数据 all_data = cursor.fetchall() # scroll 绝对位置移动 cursor.scroll(3,mode='absolute') # scroll 相对位置移动 cursor.scroll(3,mode='relative') conn.commit() cursor.close() conn.close()