执行SQL语句
执行SQL前,需要先通过调用Connection类的cursor方法获取到cursor,然后通过cursor调用execute方法执行SQL语句。
如果需要获取结果集,可通过Cursor类中的fetch系列的方法进行获取。
函数原型
- 执行SQL语句并自动提交。
#创建cursor c=conn.cursor() #设置自动提交 conn.autocommit(True) #调用execute方法创建表 c.execute("create table tablename(relational_properties)") #调用execute方法插入数据 c.execute("insert into tablename values(expression [ , ... ])") #关闭cursor c.close()
- SQL语句回滚。手动提交。
conn.rollback()
- 手动提交SQL语句。
conn.commit()
- 执行SQL语句并获取元组。
#调用execute方法获取查询结果 c.execute("select * from tablename") #用fetchall方法获取所有结果 row =c.fetchall()
示例
- 执行SQL语句并自动提交
#创建cursor c=conn.cursor() #设置自动提交 conn.autocommit(True) #调用execute方法创建表 c.execute("create table testexecute(a int,b char(10),c date)") #调用execute方法插入数据 c.execute("insert into testexecute values(1,'s','2012-12-13')") #关闭cursor c.close() #关闭数据库连接 conn.close()
- 执行SQL语句并回滚或手动提交。
#加载pyzenith模块 import pyzenith #以omm用户连接数据库,密码gaussdb_123,端口号1888。 host='192.168.0.1' username='omm' password='gaussdb_123' port='1888' conn=pyzenith.connect(host,username,password,port) #创建cursor c=conn.cursor() #调用execute方法创建表 c.execute("create table testexecute(a int,b char(10),c date)") #调用execute方法插入数据 c.execute("insert into testexecute values(1,'s','2012-12-13')") #回滚事务 或 提交事务 conn.rollback() 或 conn.commit() #关闭cursor c.close() #关闭数据库连接 conn.close()
- 执行SQL语句并获取元组。
#加载pyzenith模块 import pyzenith #以omm用户连接数据库,密码gaussdb_123,端口号1888。 host='192.168.0.1' username='omm' password='gaussdb_123' port='1888' conn=pyzenith.connect(host,username,password,port) #创建cursor c=conn.cursor() #调用execute方法创建表 c.execute("create table testexecute(a int,b char(10),c date)") #调用execute方法插入数据 c.execute("insert into testexecute values(1,'s','2012-12-13')") #调用execute方法获取查询结果 c.execute("select * from testexecute") #用fetchall方法获取所有结果 row =c.fetchall() #关闭cursor c.close() #关闭数据库连接 conn.close()
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」关注作者【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。评论
- 执行SQL语句并回滚或手动提交。
- SQL语句回滚。手动提交。