学习Python①:Phthon操作Ms SQL Server数据库

  网络上说,目前最火的开发语言是Python,它的功能强大并且应用范围很广,刚好最近要做一个小项目,就是通过一个小程序来管理交换机,于是在网络找资料来学习。

  现在网络发达,学一门编程语言太容易了,遇到问题找资料容易,不像以前资料少,为了找一个API的使用说明都费劲。

  学Python麻烦之一是搭建编程环境,下载和安装相应的插件,好在有网络,终会解决。

  1、Python版本众多,我下载了3.8、3.9,安装后不太顺利,换成3.7就好了,稳定。

  2、开发工具是PyCharm,我们使用的是代理上网,折腾插件很费劲。

  3、Pymssql的安装在pycharm中安装不顺利,反复折腾,后来使用在dos下安装,即pip install pymssql-2.1.5-cp37-cp37m-win_amd64.whl。

  4、重启了几次的pycharm才安装好,可惜没代码提示,但是可以编程了。

  5、乱码,最后在获取字段(字符串)的后面加.encode('latin1').decode('gbk'))就可以正常显示了。

  6、有用的网址:

  ● https://docs.python.org/zh-cn/3/

  ● https://docs.python.org/zh-cn/3.7/library/

  ● https://pypi.org/project/paramiko/#files

  ● https://riverbankcomputing.com/software/pyqt/download

  建立连接很容易,对数据记录的操作是通过游标进行的。

  下面是成功的代码:

import pymssql # 对MS SQL Server的操作
import sys

print(sys.getdefaultencoding())

定义数据库的连接

DBSeverIP="1.2.3.4"
DBUser="user"
DBPassword="pass"
DBDatabase="mineDB"
DBCharset="utf-8"
DBConn=pymssql.connect(DBSeverIP,DBUser,DBPassword,DBDatabase,DBCharset)
if DBConn:
print("数据库连接成功!")

定义访问游标

DBCursor=DBConn.cursor()

增加数据记录

StrInsertSQL="insert into HaoRTable values(%s,%s,%s,%s,%s,%s)"
DBCursor.execute(StrInsertSQL,("777","777","23","24","25","26"))
DBConn.commit()

删除数据记录

StrInsertSQL="delete from HaoRTable where c01=%s"
DBCursor.execute(StrInsertSQL,("44"))
DBConn.commit()

修改数据记录

StrUpdateSQL="update HaoRTable set c02=%s where c01=%s"
DBCursor.execute(StrUpdateSQL,("新的表","33"))
DBConn.commit()

查询返回的数据

StrQuerySQL="select * from HaoRTable"
DBQueryResult=DBCursor.execute(StrQuerySQL)

读取查询结果(fetchall,获取全部的数据记录)

DBTable=DBCursor.fetchall()
for i in range(len(DBTable)):
print("第{}行".format(i),DBTable[i][1].encode('latin1').decode('gbk'),DBTable[i][2].encode('latin1').decode('gbk'),DBTable[i][3].encode('latin1').decode('gbk'))
print("第{}行".format(i),DBTable[i][0],DBTable[i][1].encode('latin1').decode('gbk'),DBTable[i][2].encode('latin1').decode('gbk'))

读取查询结果(fetchall,获取一条数据记录)

DBQueryResult=DBCursor.execute(StrQuerySQL)
DBTableRow=DBCursor.fetchone()
while DBTableRow:
print(DBTableRow[1].encode('latin1').decode('gbk'),DBTableRow[2].encode('latin1').decode('gbk'),DBTableRow[3].encode('latin1').decode('gbk'))
DBTableRow=DBCursor.fetchone()

DBCursor.close() #关闭游标
DBConn.close() #关闭数据库连接

猜你喜欢

转载自blog.51cto.com/dawn0919/2585553