在表中插入行最简单的方法是使用非参数化 INSERT 语句,这意味着值作为 SQL 语句的一部分来指定。会为每个新行构建和执行一条新语句。在前面的示例中,需要游标才能执行 SQL 语句。
以下示例程序在示例数据库中插入两名新客户。断开连接前,它将事务提交到数据库。
import sqlanydb # Create a connection object, then use it to create a cursor con = sqlanydb.connect( userid="DBA", pwd="sql" ) cursor = con.cursor() cursor.execute("DELETE FROM Customers WHERE ID > 800") rows = ((801,'Alex','Alt','5 Blue Ave','New York','NY', 'USA','10012','5185553434','BXM'), (802,'Zach','Zed','82 Fair St','New York','NY', 'USA','10033','5185552234','Zap')) # Set up a SQL INSERT parms = ("'%s'," * len(rows[0]))[:-1] sql = "INSERT INTO Customers VALUES (%s)" % (parms) print sql % rows[0] cursor.execute(sql % rows[0]) print sql % rows[1] cursor.execute(sql % rows[1]) cursor.close() con.commit() con.close() |
另一种方法是使用参数化的 INSERT 语句,这意味着问号用作值的占位符。executemany 方法用于为每个行集成员执行 INSERT 语句。新行的值作为单个参数提供给 executemany 方法。
import sqlanydb # Create a connection object, then use it to create a cursor con = sqlanydb.connect( userid="DBA", pwd="sql" ) cursor = con.cursor() cursor.execute("DELETE FROM Customers WHERE ID > 800") rows = ((801,'Alex','Alt','5 Blue Ave','New York','NY', 'USA','10012','5185553434','BXM'), (802,'Zach','Zed','82 Fair St','New York','NY', 'USA','10033','5185552234','Zap')) # Set up a parameterized SQL INSERT parms = ("?," * len(rows[0]))[:-1] sql = "INSERT INTO Customers VALUES (%s)" % (parms) print sql cursor.executemany(sql, rows) cursor.close() con.commit() con.close() |
虽然两个示例似乎都是将行数据插入表中的较为合适的方法,但后一种方法更佳,原因有两点。如果数据值是通过提示来输入而获取的,在注入包含 SQL 语句的游荡数据时,第一个示例容易受到影响。第一个示例需要为每个要插入到表中的行调用 execute 方法。而第二个示例只调用一次 executemany 方法,就可将所有行插入到表中。
![]() |
使用DocCommentXchange讨论此页。
|
版权 © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 |