python cx_oracle in语句_Python cx_Oracle.insert方法代码示例

本文介绍了如何在Python中使用cx_Oracle库进行数据库插入操作,特别是处理IN语句的情况。示例代码展示了insert方法的用法,包括设置默认序列ID和测试查询。通过示例,展示了如何构建和执行SQL INSERT语句,并获取新插入行的ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 需要导入模块: import cx_Oracle [as 别名]

# 或者: from cx_Oracle import insert [as 别名]

def insert(self, tablename, seqname=None, _test=False, **values):

"""

Inserts `values` into `tablename`. Returns current sequence ID.

Set `seqname` to the ID if it's not the default, or to `False`

if there isn't one.

>>> db = DB(None, {})

>>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True)

>>> q

>>> q.query()

'INSERT INTO foo (age, created, name) VALUES (%s, NOW(), %s)'

>>> q.values()

[2, 'bob']

"""

def q(x): return "(" + x + ")"

if values:

#needed for Py3 compatibility with the above doctests

sorted_values = sorted(values.items(), key=lambda t: t[0])

_keys = SQLQuery.join(map(lambda t: t[0], sorted_values), ', ')

_values = SQLQuery.join([sqlparam(v) for v in map(lambda t: t[1], sorted_values)], ', ')

sql_query = "INSERT INTO %s " % tablename + q(_keys) + ' VALUES ' + q(_values)

else:

sql_query = SQLQuery(self._get_insert_default_values_query(tablename))

if _test: return sql_query

db_cursor = self._db_cursor()

if seqname is not False:

sql_query = self._process_insert_query(sql_query, tablename, seqname)

if isinstance(sql_query, tuple):

# for some databases, a separate query has to be made to find

# the id of the inserted row.

q1, q2 = sql_query

self._db_execute(db_cursor, q1)

self._db_execute(db_cursor, q2)

else:

self._db_execute(db_cursor, sql_query)

try:

out = db_cursor.fetchone()[0]

except Exception:

out = None

if not self.ctx.transactions:

self.ctx.commit()

return out

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值