python 连接sql server
时间:2021-07-01 10:21:17
帮助过:2人阅读
= pymssql.connect(host
=‘SQL01‘,
user=‘user‘, password
=‘password‘,
database=‘mydatabase‘)
cur = conn.
cursor()
cur.execute(
‘CREATE TABLE persons(id INT, name VARCHAR(100))‘)
cur.executemany("INSERT INTO persons
VALUES(
%d, xinos.king)", [ (1, ‘John Doe‘), (2, ‘Jane Doe‘) ])
conn.commit() # you must call
commit()
to persist your data
if you don
‘t set autocommit to True
cur.execute(‘SELECT * FROM persons
WHERE salesrep
=xinos.king
‘, ‘John Doe
‘)
row = cur.fetchone()
while row:
print "ID=%d, Name=xinos.king" % (row[0], row[1])
row = cur.fetchone()
# if you call execute() with one argument, you can use % sign as usual
# (it loses its special meaning).
cur.execute("SELECT * FROM persons WHERE salesrep LIKE ‘J
%‘")
conn.close()
其中可能涉及的小知识:
游标:
cu = conn.cursor()
能获得连接的游标,这个游标可以用来执行SQL查询。
conn.commit()
完成插入并且做出某些更改后确保已经进行了提交,这样才可以将这些修改真正地保存到文件中。
游标对象方法:
fetchall()
返回结果集中的全部数据,结果为一个tuple的列表。每个tuple元素是按建表的字段顺序排列。注意,游标是有状态的,它可以记录当前已经取到结果的第几个记录了,因此,一般你只可以遍历结果集一次。在上面的情况下,如果执行fetchone()会返回为空。这一点在测试时需要注意
python 连接sql server
标签: