python --mysql
python3: pymysql
python2: MySQLdb
步骤:
1, 建立数据库连接对象
db = pymysql.connect("dbaddress","username","password","dbname",charset = "utf8")
2, 创建游标对象
cursor = db.cursor()
3, 使用游标对象的方法操作数据库
cursor.execute("command;");
4, 提交commit
db.commit();
5, 关闭游标对象
cursor.close()
6, 关闭数据库连接
db.close();
db连接对象支持的方法:
1, cursor() 创建游标对象
2, commit() 提交方法
3, rollback()回滚方法
4,close() 关闭连接
cursor对象支持的方法:
1, execute("SQL命令") 执行SQL命令
2, fetchone() 取得结果集的第一条记录
3,fetchmany(n)取得结果集的n条记录
4, fetchall()取得结果集的所有记录
5, close() 关闭游标对象
复制代码
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
36import pymysql # python操作mysql 步骤: # 1, 建立数据库连接 # 2, 创建游标对象 # 3, 使用游标对象的方法操作数据库 # 4, 提交commit # 5, 关闭游标对象 # 6, 关闭数据库连接 try: #创建db连接对象 db = pymysql.connect("192.168.10.16","wang","123456","wang",charset = "utf8") #创建游标对象 cursor = db.cursor() #cursor.execute("create database wang;") #如果连接的时候未指定库名,则必须use db cursor.execute("use wang;") #执行语句 # sql_create = "create table t3(id int auto_increment, name varchar(30) default '', age int default 0, score int default 0,primary key(id))engine = innodb;" # cursor.execute(sql_create) sql_insert = "insert into t3(name,age,score) values('llj',20,100),('wanghuan',18,99);" cursor.execute(sql_insert) #查询语句 sql_query = "select * from wang.t3 limit 5;" #执行查询语句;执行后,结果集保存在cursor中 cursor.execute(sql_query) # 将结果集赋值给变量,并打印 data = cursor.fetchall() print("查询结果集为:") for I in data: print(I) #事物操作,必须要提交,也可以rollback() db.commit() finally: #关闭连接 cursor.close() db.close()
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import pymysql host = "192.168.10.16" user = "wang" password = "123456" dbname = "wang" ch = "utf8" db = pymysql.connect(host, user, password, dbname, charset = ch) cur = db.cursor() try: sql_update_1 = "update t3 set age = age + 1 where name = 'llj';" sql_update_2 = "update t3 set age = age + 2 where name = 'wanghuan';" cur.execute(sql_update_1) cur.execute(sql_update_2) db.commit() print("execute successfully;") except Exception as e: db.rollback() print("execute failed, command has been rollback") cur.close() db.close()
最后
以上就是天真耳机最近收集整理的关于python-操作DB的全部内容,更多相关python-操作DB内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复