---
# System prepended metadata

title: 是不是用了python的`with as`就不必close了?

---

# 是不是用了python的`with as`就不必close了?
這是個問題不是筆記

## 1. open使用`with as`
* 經典的open
```py=
f = open('Z:\NTTU_DSA\DSA80\3eb97b1b-1dca-4a4d-bf9d-e4e85e75b8db_10803研究獎助生學習紀錄表.pdf', 'w')
f.write("Now the file has more content!")
f.close()
```
* 用with as的open
```py=
with open('Z:\NTTU_DSA\DSA80\3eb97b1b-1dca-4a4d-bf9d-e4e85e75b8db_10803研究獎助生學習紀錄表.pdf', 'w') as output_file:
    output_file.write("Now the file has more content!")
```

## 2. 所以pyodbc也能這麼做嗎?
* 經典的pyodbc
```py=
import pyodbc 
server = 'tcp:myserver.database.windows.net' 
database = 'mydb' 
username = 'myusername' 
password = 'mypassword' 
conn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';ENCRYPT=yes;UID='+username+';PWD='+ password)
cursor = conn.cursor()
# do something
cursor.execute('''
    SELECT 
        id_,
        pid
    FROM 
        user
''')
# end do something
conn.close()

```
* 用with as的pyodbc
```py=
import pyodbc 
server = 'tcp:myserver.database.windows.net' 
database = 'mydb' 
username = 'myusername' 
password = 'mypassword' 
with pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';ENCRYPT=yes;UID='+username+';PWD='+ password) as conn:
    with conn.cursor() as cursor:
        # do something
        cursor.execute('''
            SELECT 
                id_,
                pid
            FROM 
                user
        ''')
        # end do something
```

## ref
* https://medium.com/%E7%A8%8B%E5%BC%8F%E4%B9%BE%E8%B2%A8/python-with-as-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6-bc5850dee667