python之pymysql模块

模块安装

pip install pymysql

执行sql语句

 1 import pymysql
 2 #通过pymysql下的connect函数来建立一个传输通道,连接本地mysql的所以host地址是127.0.01,3306是mysql的端口,user是你mysql的用户名,passwd是相对应的密码,db是数据库的名称
 3  conn=pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="root",db="text1")
 4 #获取游标
 5  cursor=conn.cursor()#默认取到的是元组的形式,若想让其是字典的形式在括号中添加cursor=pymysql.crusors.DictCrusor
 6  
 7  sql="CREATE TABLE TEST(id INT,name VARCHAR(20))"
 8 
 9 #execute(oper[,params]) #执行SQL操作,可能使用参数 executemany(oper,pseq) #对序列中的每个参数执行SQL操作 
10  ret=cursor.execute(sql)
11  #返回的影响的行数 
12  print(ret)
13 
14  #以下三条适用于查询,三条命令执行以后游标自动走到下一个
15  #取第一条
16  print(cursor.fetchone())
17  #取所有
18  print(cursor.fetchall())
19  #取前3条
20  print(cursor.fetchmany(3))
21  #正数代表把光标移动到下一个位置,负数代表往上移动
22  cursor.scroll(1,mode="relative")
23  #直接移动到第一个位置
24  cursor.scroll(1,mode="absolute")
25 
26 
27 
28 
29 
30 conn.commit()
31 #close() #关闭连接之后,连接对象和它的游标均不可用
32  cursor.close()
33 conn.close()
View Code
 1 往表中写入数据时, 执行execute 方法, 有两种方式, 一种是直接execute(sql), 然后commit 完成, sql里是写入的sql 语句
 2 
 3 
 4     
 5 cursor.execute("insert into stu_info (name, age, sex) values ('jonie',25,'man')")
 6 db.commit()
 7 
 8 这会直接写入表中,但还有另外一种方式,
 9 execute 可以接受两个参数, 第一个参数是sql语句, 不过这个sql中的values的内容使用占位符%s表示,第二个参数是实际的写入的values列表, 如下:
10 
11 
12     
13 13cursor.execute("insert into stu_info (name, age, sex) values (%s,%s,%s)", ("annie",25, "man"))
14 db.commit()
15 
16 这种方式与第一中方式相比, 更清晰一些, 安全性也更好, 能有效防止sql注入
17 
18 另外, cursor还有一个executemany, 参数和execute一样, 不过第二个参数可以传递多列表值, 达到多次执行某个语句的效果
19 cursor.executemany("insert into stu_info (name, age, sex) values (%s,%s,%s)",(("fd",26,"femal"),("yueyue",28,"femal")))
20 db.commit()
21 这里实际上就是执行了两次插入操作
补充

猜你喜欢

转载自www.cnblogs.com/jqpy1994/p/9556113.html