1、update delete insert 这种语句都需要commit或者直接在连接数据库的时候加上autocommit=True
1
2
3
4
5
6
7
8
9
10
|
import pymysql conn = pymysql.connect( host = "", user = "jxz" , password = "", db = "jxz" , port = 3306 , charset = "utf8" , autocommit = True |
)#连接数据库
2、数据库内容比较多的时候
1
2
3
4
5
|
for line in cursor: #表数据比较多的时候就用它 print (line) #还有其他的间接的方式 # result = cursor.fetchmany(5) #获取n条 #cursor.execute("select * from students limit 5;") |
3、想要获取到字典型的数据,在写游标的时候加上:cursor = conn.cursor(pymysql.cursors.DictCursor) #建立游标
1
|
cursor = conn.cursor(pymysql.cursors.DictCursor) #建立游标 |
4、整体的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import pymysql conn = pymysql.connect(host = '', user = 'jxz' , password = '', db = 'jxz' , port = 3306 , autocommit = True , charset = 'utf8' ) #链接数据库 cursor = conn.cursor() #游标 #查看当前所有的表 #cursor.execute('create table lmmlmm(num int,str varchar (20));') cursor.execute( 'insert into lmmlmm (num,str)values("1","limiaomiao");' ) conn.commit() result = cursor.fetchall() cursor.close() conn.close() print (result) |
5、可以将连接数据库的参数写成集合的形式,并且用**转换成key,value的格式,方便调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import pymysql mysql_info = pymysql.connect( host = "", user = "jxz" , password = "", db = "jxz" , port = 3306 , charset = "utf8" , autocommit = True ) #连接数据库 ##**后面只能是字典,且能够转换成key,value def execute_sql(sql,more = False ,db_info = None ): # select *from user where id=1; if db_info: conn = pymysql.connect( * * db_info) else : conn = pymysql.connect( * * mysql_info) |
到此这篇关于python连接数据库的重要事项的文章就介绍到这了,更多相关python连接数据库内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_39349045/article/details/113918958