2017-04-26 114 views
1

請幫助我通過python編程語言的幫助來從MSSQL Server獲取數據。我需要簡單的實現,如使用select命令獲取所有表數據並使用過程來操作數據。還有哪些模塊將用於構建python和MSSQL之間的通信。通過Python從MSSQL獲取數據

+0

您是否試過使用[pymssql](http://pymssql.org/en/stable/)? –

+0

歡迎!把你的代碼示例,你想要的。並訪問鏈接** [如何問](http://stackoverflow.com/help/mcve)** –

回答

0
import pymssql 
conn = 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, %s)", \ 
    [ (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=%s', 'John Doe') 
row = cur.fetchone() 
while row: 
    print "ID=%d, Name=%s" % (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() 
+0

如果它解決了你的查詢然後upvote並接受這個答案 –

2

我用這個代碼,它的工作完美。

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') 
row = cursor.fetchone() 
while row: 
    print("ID=%d, Name=%s" % (row[0], row[1])) 
    row = cursor.fetchone() 

conn.close()