“如何脱衣”;(),";从Python、PyODBC、SQL返回?
我收集了一堆需要用Python和PyODBC更新的SQL ID:“如何脱衣”;(),";从Python、PyODBC、SQL返回?,python,sql-server,pyodbc,Python,Sql Server,Pyodbc,我收集了一堆需要用Python和PyODBC更新的SQL ID: import pyodbc cnxn = pyodbc.connect('DSN=YesOne;PWD=xxx') cursor = cnxn.cursor() cursor.execute("SELECT ID FROM One.dbo.Two WHERE STATUS = 'OnGoing' AND ID = ''") 我还有第二段代码更新ID: cursor.execute("Update One.dbo.Two SET
import pyodbc
cnxn = pyodbc.connect('DSN=YesOne;PWD=xxx')
cursor = cnxn.cursor()
cursor.execute("SELECT ID FROM One.dbo.Two WHERE STATUS = 'OnGoing' AND ID = ''")
我还有第二段代码更新ID:
cursor.execute("Update One.dbo.Two SET STATUS = 'Completed', Modified = 'Today' WHERE ID = '1051'")
问题是,当我查看之前在Python中捕获的ID时,我会得到以下任一结果:
row = cursor.fetchall()
f row:
print row
[(1016,),(1017,),(1019,),(1020,
), (1021, ), (1025, ), (1026, ),
(1027, ), (1029, ), (1048, ), (1049,
)]
或
(1020,)
我只需要数字,以便运行脚本的第二部分:
WHERE ID = '1051'"
部分。我试过:
count = len(row)
while count > 0:
newrow = row[count-1]
print 'SELECT ID FROM One.dbo.Two WHERE ID = ' + str(newrow)
count = count-1
它给了我:
从One.dbo.Two中选择ID,其中ID=(1049,)从One.dbo.Two中选择ID,其中ID=(1048,)
等等 我试着:
str(row[1]).lstrip('(),')
我得到:
"1017),
如何从ID中删除字符,以便重用ID
谢谢
阿德里安首先:
rows = [x[0] for x in cursor.fetchall()]
然后放弃可怕的while循环:
for row in rows:
print 'SELECT ID FROM One.dbo.Two WHERE ID = %s' % row
我认为问题在于您正在从列表中访问元组,因此需要指定列表中的位置和元组中的位置:
row = cursor.fetchall()
f row:
print row
print row[3]
print row[3][0]
产出:
[(1016, ), (1017, ), (1019, ), (1020, ), (1021, )]
(1020, )
1020
[(1016, ), (1017, ), (1019, ), (1020, ), (1021, )]
(1020, )
1020