Skip to content

Commit

Permalink
更新博文:pymssql-unicode-error
Browse files Browse the repository at this point in the history
  • Loading branch information
Young-Lord authored Nov 1, 2023
1 parent 7ba3a3f commit 7dc2ae1
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion _posts/2023-08-29-pymssql编码问题报错UnicodeDecodeError.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
tags: [SQL Server, Python, bugfix]
title: "pymssql编码问题报错UnicodeDecodeError: 'gbk' codec can't decode byte..."
slug: pymssql-unicode-error
last_modified_at: 2023-8-29
last_modified_at: 2023-11-1
---

## TLDR

一眼以概之,就是拿`pyodbc`换掉`pymssql`

### 安装`msodbc`驱动

#### Windows
Expand All @@ -21,6 +23,8 @@ last_modified_at: 2023-8-29

`pip install pyodbc`安装`pyodbc`,并将代码里的`pymssql`改为`pyodbc`

#### 连接数据库

把代码里的`connect`如下更改:

```python
Expand All @@ -46,6 +50,26 @@ pyodbc.connect(f'DRIVER={{ODBC Driver 18 for SQL Server}};SERVER={Config.DATABAS

(对于Linux,你必须使用DSN配置连接信息而**不能使用上面的方法**,具体自行参见[Wiki](https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Linux)

#### 执行SQL

把代码里的`Cursor`对象的`execute`方法中的`%s`, `%d`等占位符全部换为`?`,即:

```python
db.execute(
"insert into [aa] ([name],[value]) values (%s, %d)",
(name, value),
)
```

改为:

```python
db.execute(
"insert into [aa] ([name],[value]) values (?, ?)",
(name, value),
)
```

完事!

## 其他解决方案
Expand Down

0 comments on commit 7dc2ae1

Please sign in to comment.