Section 162.1: 连接到服务器、创建表、查询数据

安装包:

$ pip install pymssql
import pymssql

SERVER = "servername"
USER = "username"
PASSWORD = "password"
DATABASE = "dbname"

connection = pymssql.connect(server=SERVER, user=USER,
                             password=PASSWORD, database=DATABASE)

cursor = connection.cursor() # 要将字段作为字典访问,请使用 cursor(as_dict=True)
cursor.execute("SELECT TOP 1 * FROM TableName")
row = cursor.fetchone()

######## 创建表 ########
cursor.execute(
  """CREATE TABLE posts (
  post_id INT PRIMARY KEY NOT NULL,
  message TEXT,
  publish_date DATETIME
  )""")

######## 向表中插入数据 ########
cursor.execute("""INSERT INTO posts VALUES(1, "Hey There", "11.23.2016")""")

# 将工作提交到数据库
connection.commit()

######## 遍历结果 ########
cursor.execute("SELECT TOP 10 * FROM posts ORDER BY publish_date DESC")
for row in cursor:
  print("Message: " + row[1] + " | " + "Date: " + row[2])
  # 如果你将 as_dict=True 传递给 cursor
  # print(row["message"])

connection.close()

如果你的工作与SQL表达式有关,你可以做任何事情,只需将这些表达式传递给execute方法(CRUD操作)。

有关with语句、调用存储过程、错误处理或更多示例,请查看:pymssql.org