Python 中怎样连接数据库(python,编程语言)

时间:2024-04-27 23:45:49 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

首先是需要安装Python, 根据操作系统选择对应平台的Pyhon版本,可以在官网下载。

Python 中怎样连接数据库

然后就是安装 pyodbc,在联网情况下,打开 python 软件,输入:pip install pyodbc

等待安装完成。然后我们就可以对数据库进行操作了,比如:连接、查询、插入、修改、删除等操作。

下面主要介绍如何实现对数据库的操作:

***,连接数据库。从GitHub上可以查询到如下 pyodbc 连接 SQL Server 的要求:

Microsoft have written and distributed multiple ODBC drivers for SQL Server:

  • {SQL Server} - released with SQL Server 2000

  • {SQL Native Client} - released with SQL Server 2005 (also known as version 9.0)

  • {SQL Server Native Client 10.0} - released with SQL Server 2008

  • {SQL Server Native Client 11.0} - released with SQL Server 2012

  • {ODBC Driver 11 for SQL Server} - supports SQL Server 2005 through 2014

  • {ODBC Driver 13 for SQL Server} - supports SQL Server 2005 through 2016

  • {ODBC Driver 13.1 for SQL Server} - supports SQL Server 2008 through 2016

  • {ODBC Driver 17 for SQL Server} - supports SQL Server 2008 through 2017

importpyodbccnxn=pyodbc.connect('DRIVER={SQLServer};SERVER=192.168.1.6;DATABASE=test;UID=sa;PWD=Admin123')

DRIVER:对应数据库版本的驱动器,SQL server 2000是“SQL Server”;

SERVER:数据库服务器名称或者数据库服务器的IP地址;

DATABASE:数据库名称,UID:账号,PWD:密码。

第二,查询数据库

cursor = cnxn.cursor() #获得游标

cursor.execute("select * from test.dbo.JZGK") #执行SQL的查询语句

rows = cursor.fetchall() #获得所有数据,返回一个list对象

for row in rows: #使用for循环对查询的数据遍历并打印出来

print(row.LoopName, row.Press,row.Temp,row.Flow,row.Time_Stamp)

Python 中怎样连接数据库

第三,数据库中插入数据

import pyodbc

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.1.6;DATABASE=test;UID=sa;PWD=Admin123')

cursor = cnxn.cursor()

cursor.execute("insert into products(id, name) values ('3', 'abd')") #使用SQL的insert语句向数据库的表products插入一条记录

cnxn.commit() #操作提交,如果中途出错,或连接中断,则会发生数据回流,不会影响到数据库原有数据。

第四,数据库中删除数据

cursor.execute("delete from products where id <> ?", '1') #使用SQL的delete 语句删除数据

print('Deleted{}inferiorproducts'.format(cursor.rowcount))cnxn.commit()

Python 中怎样连接数据库

第五,数据库中更新数据

cursor.execute("UPDATE test SET LoopName=FIQ1005 WHERE LoopName=FIQ1004) #使用SQL的UPDATE 语句更新数据

cnxn.commit()cnxn.close()

注意:所有的SQL操作完成后需要关闭数据库连接

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Python 中怎样连接数据库的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Redis Cluster如何实现写安全的重要特性下一篇:

6 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18