如何用python遍历SQLServer数据库中某个表的所有记录,并修改。 5C

想用python遍历某个数据库中的一个表,依次读出每条记录,并修改保存。
请问该如何编写代码?谢谢

2个回答

declare @row varchar(30)
declare @tbname varchar(30)
DECLARE string_find_cursor CURSOR FAST_FORWARD FOR

SELECT [name]

FROM sysobjects where type='U' and name like 'A%'
ORDER BY [name]

OPEN string_find_cursor

FETCH NEXT FROM string_find_cursor

INTO @tbname

WHILE @@FETCH_STATUS = 0

BEGIN

--select @row=count(*) from @tbname
select @row=rows from sysindexes where id = object_id(cast(@tbname as varchar(30))) and indid in (0,1)
if(cast(@row as int))>0
print @tbname+' '+@row+' '+'select * from '+@tbname
FETCH NEXT FROM string_find_cursor

INTO @tbname

END

CLOSE string_find_cursor

DEALLOCATE string_find_cursor

参考 : https://blog.csdn.net/my98800/article/details/76602277

你可以看看

应该要表明Python版本MSSql版本,不过可以先参考代码:

from os import getenv
import pymssql

server = getenv("PYMSSQL_TEST_SERVER")
user = getenv("PYMSSQL_TEST_USERNAME")
password = getenv("PYMSSQL_TEST_PASSWORD")

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
    DROP TABLE persons
CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(100),
    salesrep VARCHAR(100),
    PRIMARY KEY(id)
)
""")
cursor.executemany(
    "INSERT INTO persons VALUES (%d, %s, %s)",
    [(1, 'John Smith', 'John Doe'),
     (2, 'Jane Doe', 'Joe Dog'),
     (3, 'Mike T.', 'Sarah H.')])
# you must call commit() to persist your data if you don't set autocommit to True
conn.commit()

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cursor:
    print("ID=%d, Name=%s" % (row['id'], row['name']))

conn.close()
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问