Skip to content

Pymssql

pymssql — pymssql 2.2.2.dev0+gff84c14.d20210416 documentation

连接

# 连接 autocommit 自动修改操作
conn = sql.connect(serverName, userName, password, autocommit=True)
cursor = conn.cursor()
# 关闭连接
conn.close()

可能遇到的错误:

18456:先用 windows 身份验证登录,右击数据库(不是里面数据库那个文件夹,是最外面那个,图标是数据库),右击属性,安全性,服务器验证身份改为 SQL Server 和 Windows 身份验证模式

233:打开 SQL Server 配置管理器,SQL Server网络配置,MSSQLSERVER的协议,启用 TCP / IP,最好再重启一下 SQL Server配置管理器(本地)中的 SQL Server

执行指令

# 执行
cursor.execute('sql语句')
# 调用存储过程
cursor.callproc('FindPerson', ('Jane Doe',)) # 存储过程名  参数

获取结果

cnt = cursor.fetchone()[0] # 获取第一行

# 获取多行
row = cursor.fetchone() 
while row:
    print("ID=%d, Name=%s" % (row[0], row[1]))
    row = cursor.fetchone()

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cursor:
    print('row = %r' % (row,))

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

注意事项:一条链接在任何时候只会有一个Cursor对象处于查询状态

SQL 相关

CONVERT()

SQL Server CONVERT() 函数 (w3school.com.cn)

登录名与用户

SQLServer —— 用户权限操作 - 徐林俊