python:数据库连接操作入门

python:数据库连接操作入门

原文位置:
python:数据库连接操作入门 - JYRoy - 博客园 https://www.cnblogs.com/jyroy/p/9429897.html
模块#

1 import pymssql,pyodbc

模块说明#
  pymssql和pyodbc模块都是常用的用于SQL Server、MySQL等数据库的连接及操作的模块,当然一些其他的模块也可以进行相应的操作,类似adodbapi、mssql、mxODBC等,我们在实际用的时候选择其中一个模块就好,对于每一个模块都有相应的支持版本和支持平台,大家可以自行查阅文档https://wiki.python.org/moin/SQL%20Server

模块安装 #

1 pip install pymssql

关于pip的使用我在我的另一篇博客里提到了https://www.cnblogs.com/jyroy/p/9410593.html

模块使用#
  我们利用python来进行数据库的操作,那么第一步就应该是连接数据库,这里我们用pymssql模块中的connect方法连连接,在pyodbc模块中同样也是利用connect方法。

使用connect创建连接对象
connect.cursor创建游标对象,SQL语句的执行基本都在游标上进行
cursor.executeXXX方法执行SQL语句,cursor.fetchXXX获取查询结果等
调用close方法关闭游标cursor和数据库连接

pymssql模块连接

复制代码
‘’’
pymssql模块连接SQL Server数据库
‘’’

import pymssql   

 '''格式1'''
host= "XXXXXXXXXXXX"  # 数据库服务器名称或IP
user = "test"
password = "123"
database = "test"

conn = pymssql.connect(host, user, password, database)

'''格式2'''
conn = pymssql.connect(host='XXXXXXXXXXXX', user="test", password="123", database="test")

复制代码

pyodbc模块连接

 import pyodbc

    conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=test;DATABASE=test;UID=user;PWD=password')

不同的SQL server版本对应的DRIVER字段不同。对应关系如下:

{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
  使用pyodbc需要安装微软官方的Native Client(没有安装会报错IM002),安装SQL server management studio会自动附带安装(控制面板里可以看到安装的版本)。如果没有安装过需要在https://msdn.microsoft.com/en-us/data/ff658533.aspx下载安装(sqlncli.msi)。建议选择与远程数据库版本相对应的Native Client。如果本地安装的Native Client是高版本,则DRIVER={SQL Server Native Client 11.0}需要填写的是本地的高版本。

获取数据库内容#

这里涉及到游标的使用(游标大家有不理解的可以参考一下这个大佬的博客https://www.cnblogs.com/selene/p/4480328.html)

1     '''
2     游标的使用
3     '''
4     cursor_1 = conn.cursor()     #获取游标
5 
6     cursor_1.execute("select Sno from student")    #执行语句
7 
8     print (cursor_1.fetchone())              #结果是元组,fetchone()获取查询结果
9  

fetchone() :返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None

fetchall() :返回多个元组,即返回多个记录(rows),如果没有结果 则返回 ()

 1     '''
 2     fetchall()的使用
 3     '''
 4     cursor_2 = conn.cursor()
 5 
 6     cursor_2.execute("select Sno, Sname from students")
 7 
 8     rows = cursor_2.fetchall()
 9 
10     for row in rows:
11         print(row.Sno, row.Sname)

由于execute返回的是cursor本身,所以如果你需要一次直接获取所有内容可以直接使用cursor本身来获取

1 cursor.execute(“select Sno, Sname from students”):
2
3 for row in cursor:
4 print(row.Sno, row.Sname )

关于游标这里还存在一个要向大家专门说明的地方,

就是一个连接一次只能有一个游标的查询处于活跃状态,具体什么意思大家可以看下面的代码。

1     cursor_1 = conn.cursor()     #获取游标
2     cursor_1.execute("select Sno from student")    #执行语句
3 
4     cursor_2 = conn.cursor()
5     cursor_2.execute("select * from student where Sno=1")
6 
7     print (cursor_1.fetchall())             #显示的是cursor_2的查询结果
8     print (cursor_2.fetchall())             #不显示任何结果

提供一个解决的办法

1      '''解决上述问题'''
 2 
 3     cursor_1.execute("select Sno from student")
 4     cursor_list_1 = cursor_1.fetchall()   #用list把结果存储下来
 5 
 6     cursor_2.execute("select * from student where Sno=1")
 7     cursor_list_2 = cursor_2.fetchall()
 8 
 9     print (cursor_list_1)               #通过print list来获取cursor_1的结果
10     print (cursor_list_2)    

在游标的正常使用中游标获取的查询结果,一行为一个元组。

我们在实际使用中可以根据需求,用 as_dict 方法返回一个字典变量,其中字典的Key为数据表的列名

 1     '''游标返回行为字典变量'''
 2 
 3     cursor_3 = conn.cursor(as_dict=True)      #创建游标时指定as_dict参数来使游标返回字典变量
 4     cursor_3.execute("select * from student")
 5 
 6     for row in cursor_3:
 7         print('ID=%d' % row['Sno'])    #键名为列表的列名  {Sno:ID}
 8     
 9     print (cursor_3.fetchone())
10     
11     conn.close()     #调用close方法关闭游标cursor和数据库连接

大家如果觉得上面的代码写起来看上去太长,给大家提供一个代码量小的数据库操作解决办法

就是 with语句,即上下文管理器,它的好处一个是代码的集成度高,一个是省去显示的调用close方法关闭连接和游标

1     '''
 2     使用with语句(上下文管理器)
 3     '''
 4 
 5     '''通过使用with语句来省去显示的调用close方法关闭连接和游标'''
 6     with pymssql.connect(host='LAPTOP-3OTJHAG9', user="sa", password="123", database="TEST") as conn:    
 7 
 8     #相当于 conn = pymssql.connect(host='XXXXXXXXXXXX', user="test", password="123", database="test")
 9 
10         with conn.cursor(as_dict=True) as cursor_4:
11             cursor_4.execute('select * from student')
12             for row in cursor_4:
13                 print ('ID=%d' %(row['Sno']))

关于数据库的增删改#

增删改数据库的内容也是直接传递SQL语句给execute方法。但要注意运行之后需要用commit提交变更

1 cursor.execute("insert into students(id, name) values ('123', 'My name')")
2 conn.commit()    

3 cursor.execute("delete from studnts where id=‘123’")

4 conn.commit()
 

关于pymssql模块,还有不明白的大家可以看下官网http://www.pymssql.org/

作者:JYRoy

出处:https://www.cnblogs.com/jyroy/p/9429897.html

转载请在文章明显位置注明作者及出处。

分类: Python, 数据库
标签: python, 数据库, SQL Server, pymssql

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,我们可以使用多种数据库管理系统(DBMS)来存储和管理数据。以下是Python入门数据库的一些基本知识和示例: 1. 首先,我们需要安装Python的数据库API(Application Programming Interface)。Python的DB-API是一个标准的Python编程接口,用于连接和操作各种数据库。常用的Python数据库API有:MySQLdb、psycopg2、sqlite3等。 2. 接下来,我们需要连接到数据库。连接到数据库的方法因所使用的数据库而异。以下是连接到SQLite数据库的示例: ```python import sqlite3 # 连接到SQLite数据库 conn = sqlite3.connect('example.db') ``` 3. 创建表格。在数据库中,我们需要创建表格来存储数据。以下是创建一个名为“users”的表格的示例: ```python import sqlite3 # 连接到SQLite数据库 conn = sqlite3.connect('example.db') # 创建一个名为“users”的表格 conn.execute('''CREATE TABLE users (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL);''') ``` 4. 插入数据。在表格中插入数据的方法因所使用的数据库而异。以下是向“users”表格中插入一条数据的示例: ```python import sqlite3 # 连接到SQLite数据库 conn = sqlite3.connect('example.db') # 向“users”表格中插入一条数据 conn.execute("INSERT INTO users (ID, NAME, AGE) \ VALUES (1, 'Tom', 20)") ``` 5. 查询数据。查询数据的方法因所使用的数据库而异。以下是从“users”表格中查询所有数据的示例: ```python import sqlite3 # 连接到SQLite数据库 conn = sqlite3.connect('example.db') # 从“users”表格中查询所有数据 cursor = conn.execute("SELECT * from users") for row in cursor: print("ID = ", row[0]) print("NAME = ", row[1]) print("AGE = ", row[2]) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值