python连接数据库操作入门教程

1.模块

import pymssql,pyodbc
模块说明

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

模块安装
pip install pymssql

2.模块使用

我们利用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}需要填写的是本地的高版本。

获取数据库内容

这里涉及到游标的使用

'''
    游标的使用
    '''
    cursor_1 = conn.cursor()     #获取游标

    cursor_1.execute("select Sno from student")    #执行语句

    print (cursor_1.fetchone())              #结果是元组,fetchone()获取查询结果

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

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

'''
    fetchall()的使用
    '''
    cursor_2 = conn.cursor()

    cursor_2.execute("select Sno, Sname from students")

    rows = cursor_2.fetchall()

    for row in rows:
        print(row.Sno, row.Sname)

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

 cursor.execute("select Sno, Sname from students"):
 
 for row in cursor:
     print(row.Sno, row.Sname )

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

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

cursor_1 = conn.cursor()     #获取游标
cursor_1.execute("select Sno from student")    #执行语句

cursor_2 = conn.cursor()
cursor_2.execute("select * from student where Sno=1")

print (cursor_1.fetchall())             #显示的是cursor_2的查询结果
print (cursor_2.fetchall())             #不显示任何结果

提供一个解决的办法

	'''解决上述问题'''

    cursor_1.execute("select Sno from student")
    cursor_list_1 = cursor_1.fetchall()   #用list把结果存储下来

    cursor_2.execute("select * from student where Sno=1")
    cursor_list_2 = cursor_2.fetchall()

    print (cursor_list_1)               #通过print list来获取cursor_1的结果
    print (cursor_list_2)

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

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

	'''游标返回行为字典变量'''

    cursor_3 = conn.cursor(as_dict=True)      #创建游标时指定as_dict参数来使游标返回字典变量
    cursor_3.execute("select * from student")

    for row in cursor_3:
        print('ID=%d' % row['Sno'])    #键名为列表的列名  {Sno:ID}

    print (cursor_3.fetchone())

    conn.close()     #调用close方法关闭游标cursor和数据库连接

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

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

    '''
    使用with语句(上下文管理器)
    '''
	#学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025

    '''通过使用with语句来省去显示的调用close方法关闭连接和游标'''
    with pymssql.connect(host='LAPTOP-3OTJHAG9', user="sa", password="123", database="TEST") as conn:

    #相当于 conn = pymssql.connect(host='XXXXXXXXXXXX', user="test", password="123", database="test")

        with conn.cursor(as_dict=True) as cursor_4:
            cursor_4.execute('select * from student')
            for row in cursor_4:
                print ('ID=%d' %(row['Sno']))
关于数据库的增删改

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

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

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

 conn.commit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值