使用python连接sql数据库
时间: 2023-10-24 20:30:31 浏览: 94
python连数据库
使用Python连接SQL数据库可以使用不同的模块,比如mysql.connector和pymssql。对于mysql.connector模块,首先需要通过pip install mysql.connector或者pip3 install mysql.connector安装该模块。接下来,可以使用以下代码来连接并查询MySQL数据库:
```python
import mysql.connector
mydb = mysql.connector.connect(host="localhost", port=3308, user="root", passwd="1234Abcd", database="telusko")
mycursor = mydb.cursor()
mycursor.execute("select * from student")
result = mycursor.fetchall()
print(result)
for i in result:
print(i)
```
其中,需要根据实际情况修改host、port、user、passwd和database参数来连接到相应的MySQL数据库。这段代码将连接到名为"telusko"的数据库,并执行select语句查询student表中的数据。查询结果将保存在result变量中,并打印出来。
对于pymssql模块,需要先通过pip install pymssql安装该模块。然后,可以使用以下代码连接并查询SQL Server数据库:
```python
import pymssql
connect = pymssql.connect('服务器名称', '用户名', '密码', '库名')
if connect:
print("连接成功!")
cursor = connect.cursor()
sql = "select id, name, sex from student"
cursor.execute(sql)
row = cursor.fetchone()
while row:
print("id=%s, Name=%s, Sex=%s" % (row<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [使用python连接sql数据库](https://blog.csdn.net/weixin_41855010/article/details/107812278)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Python - python如何连接sql server数据库](https://blog.csdn.net/Ainwa/article/details/122071738)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文