python3 + pymssql中文乱码和sql传递参数的问题

 

1、sql传递参数:

cursor.execute(str_sql, m)

2、中文字段显示乱码:连接数据库时指定编码:charset='GBK'

with pymssql.connect(self.host, self.user, self.password, self.dataBaseName, timeout=10, charset='GBK') as conn:

with conn.cursor(as_dict=True) as cursor:  # 数据存放到元组列表中
                    # sqlStr = executeScriptsFromFile("./res/customRef.sql")
                     str_sql = "SELECT * FROM A WHERE id = (%s)"
                     cursor.execute(str_sql, m) # m为参数,对应上面的id
                     for row in cursor:
                         bodyList.append(row)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python连接SQL Server数据库,可以使用Pymssql模块。下面是连接SQL Server数据库的方法详解: 1. 安装Pymssql模块: 使用pip命令安装Pymssql模块: ``` pip install pymssql ``` 2. 导入Pymssql模块: 在Python程序中导入Pymssql模块: ```python import pymssql ``` 3. 连接SQL Server数据库: 使用pymssql.connect()方法连接SQL Server数据库,需要指定服务器地址、用户名、密码和数据库名称等参数: ```python conn = pymssql.connect(server='server_name', user='user_name', password='password', database='database_name') ``` 其中,server参数指定服务器地址,user参数指定用户名,password参数指定密码,database参数指定要连接的数据库名称。 4. 创建游标对象: 连接成功后,需要创建游标对象,用于执行SQL语句: ```python cursor = conn.cursor() ``` 5. 执行SQL语句: 使用游标对象的execute()方法执行SQL语句: ```python cursor.execute('SELECT * FROM table_name') ``` 6. 获取查询结果: 使用游标对象的fetchall()方法获取查询结果: ```python result = cursor.fetchall() ``` 7. 关闭连接: 查询完成后,需要关闭连接: ```python conn.close() ``` 完整的示例代码如下: ```python import pymssql # 连接SQL Server数据库 conn = pymssql.connect(server='server_name', user='user_name', password='password', database='database_name') # 创建游标对象 cursor = conn.cursor() # 执行SQL语句 cursor.execute('SELECT * FROM table_name') # 获取查询结果 result = cursor.fetchall() # 输出查询结果 for row in result: print(row) # 关闭连接 conn.close() ``` 这样就可以使用Python连接SQL Server数据库了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值