在setting中配置pymysql
1、增加
import pymysql conn = pymysql.connect( host="localhost", port=3306, database="2008a", user="root", password="123456", charset="utf8", ) cursor = conn.cursor() # 拼接语句 sql = "insert into student3(id,name,age)VALUES (0,%s,%s)" # 执行 data=("王五",18) try: cursor.execute(sql, data) conn.commit() except Exception as e: print("报错啦:",str(e)) conn.rollback() # 回滚 # 对数据库做写操作一定要记得提交assword cursor.close() conn.close()
2、增加多条数据
import pymysql conn = pymysql.connect( host="localhost", port=3306, database="2008a", user="root", password="123456", charset="utf8", ) cursor = conn.cursor() # 创建班级的sql语句 sql="insert into student3(id,name,age)VALUES (0,%s,%s)" data=[("alex1",16),("污Sir1",17),("xiaoyima1",18)] try: cursor.executemany(sql, data) # 内部实现for循环,批量执行插入语句 conn.commit() # 提交一次 except Exception as e: print("错啦!") conn.rollback() cursor.close() conn.close()
3、删除
import pymysql conn = pymysql.connect( host="localhost", port=3306, database="2008a", user="root", password="123456", charset="utf8", ) cursor = conn.cursor() # sql = "delete from info WHERE name=%s" sql = "delete from student3 WHERE id=%s" cursor.execute(sql,2) conn.commit() cursor.close() conn.close()
4、修改数据
import pymysql conn = pymysql.connect( host="localhost", port=3306, database="2008a", user="root", password="123456", charset="utf8", ) cursor = conn.cursor() sql = "update student3 set age=%s where name=%s" cursor.execute(sql,[123, "张三"]) conn.commit() cursor.close() conn.close()
5、查询数据
import pymysql conn = pymysql.connect( host="localhost", port=3306, database="2008a", user="root", password="123456", charset="utf8", ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 指定返回的数据格式为字典格式 sql = "select * from student3" cursor.execute(sql) # 返回的不是具体的数据而是受影响的行数 # ret = cursor.fetchall() # 返回所有的数据 ret = cursor.fetchone() # 返回第一条的数据 print(ret) # ret = cursor.fetchone() # 接着上一条返回一条数据 # print(ret) # ret = cursor.fetchmany(3) # 查询具体多少条数据,这里查询前三条数据 # print(ret) # # cursor.scroll(0, mode="absolute") # 绝对移动,写多少就是移到多少,这里从第1条数据开始查 # cursor.scroll(-1, mode="relative") #相对移动,这里-1表示光标往前移动数据到第2条数据,从第3条数据开始查 # ret = cursor.fetchall() # print(ret) cursor.close() conn.close()