Python——MySQL操作,使用mysql.connector

 

下载安装mysql-connector

  在命令行中执行下面的命令:

python -m pip install mysql-connector

  如果是windows上面出错的话,可以参考这篇博客:pip安装模块失败的解决办法

 

测试

  进入python中,尝试导入mysql.connector模块,如果没有报错的话,就证明模块已经成功安装,可以使用了。

C:\WINDOWS\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>  

  

 

连接MySQL

  主要是使用mysql.connector模块的connect函数,需要注意参数的名称。

import mysql.connector

# 接收参数:user, password, host, port=3306, unix_socket and database
# 返回一个MySQLConnection Object
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='test'
)

  

 

执行SQL命令

  执行sql命令之前,需要先创建一个查询,调用一下cursor()方法,这个方法名光标的意思,可以理解为,命令行中,执行sql语句之前,先要有一个光标行,在光标行中进行操作。

  调用cursor()返回的结果就是光标行(cmd,简称cmd),然后调用cmd的execute()方法,传入要执行的sql即可,不过需要注意的是,执行sql的结果,执行的结果仍旧保存在cmd中。

 

 

select查询操作

  执行select操作,使用fetchall()一次性取回所有的结果集。

import mysql.connector

# 接收参数:user, password, host, port=3306, unix_socket and database
# 返回一个MySQLConnection Object
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='test'
)

# 创建一个查询
cmd = conn.cursor()

# 执行一条原生的SQL语句,执行结果保存在cmd中,没有返回值
cmd.execute("select id, name, age from stu")
# 可以使用fetchall(),获取所有的查询结果集,返回值为一个tuple,每一个元素是一个list
res = cmd.fetchall()
print(res)
# [(1, 'LiMing', 20), (2, 'XiaoHua', 30), (3, 'LiLei', 10)]

  

  执行select操作,使用fetchone()每次只取一条记录

import mysql.connector

conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='test'
)

cmd = conn.cursor()

cmd.execute("select id, name, age from stu")

# 使用fetchone()返回一条结果集,每调用一次之后,内部指针会指向下一条结果集
print(cmd.fetchone()) # (1, 'LiMing', 20)
print(cmd.fetchone()) # (2, 'XiaoHua', 30)
print(cmd.fetchone()) # (3, 'LiLei', 10)

  

  执行select操作,使用fetchmany(num)指定每次返回的num条结果集

import mysql.connector

conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='test'
)

cmd = conn.cursor()

cmd.execute("select * from stu")

res = cmd.fetchmany(2)   # 指定返回2条记录
print(res)
# [(1, 'LiMing', 20), (2, 'XiaoHua', 30)]

res = cmd.fetchmany(1)   # 指定返回1条记录
print(res)
# [(3, 'LiLei', 10)]

  

 

insert、update、delete操作

  insert、update、delete操作,也都是使用execute方法,只需要将要执行的sql语句传入即可。

  可以在执行增删改操作之后,rowcount属性保存着受影响的记录数。

  每次插入一条数据

import mysql.connector

# 接收参数:user, password, host, port=3306, unix_socket and database
# 返回一个MySQLConnection Object
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='test'
)

# 创建一个查询
cmd = conn.cursor()

# 执行原生SQL语句
cmd.execute("insert into stu (id, name, age) values (4, 'LiBai', 99)")
print(cmd.rowcount)  # 1

cmd.execute("select * from stu")
res = cmd.fetchall()
print(res)
# [(1, 'LiMing', 20), (2, 'XiaoHua', 30), (3, 'LiLei', 10), (4, 'LiBai', 99)]

  

 

使用预处理格式(占位符格式)

  可以查看一下execute()方法的定义:

class MySQLCursor(CursorBase):
	'''
		省略很多方法和变量
	'''

	def execute(self, operation, params=None, multi=False):
        """Executes the given operation

        Executes the given operation substituting any markers with
        the given parameters.

        For example, getting all rows where id is 5:
          cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))

        The multi argument should be set to True when executing multiple
        statements in one operation. If not set and multiple results are
        found, an InterfaceError will be raised.

        If warnings where generated, and connection.get_warnings is True, then
        self._warnings will be a list containing these warnings.

        Returns an iterator when multi is True, otherwise None.
        """

  第1个参数是要执行的SQL语句,其中,参数位置先使用占位符来占位

  第2个参数是一个tuple(元组),元素值就是SQL占位符对应的参数,注意只有一个参数的时候,要写成(xxx,),后面的逗号不要忘记。

  第3个参数是一个bool值,表示第一个参数是不是多个SQL语句,如果是的话,就传入True,否则传入False。

 

  使用示例

import mysql.connector

conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='test'
)

cmd = conn.cursor()

# 注意,在SQL中的占位符,统一写%s, 具体的类型,是在tuple中,传入的参数元素类型决定
cmd.execute("select * from stu where id=%s and name=%s", (1, 'LiMing'))
res = cmd.fetchall()
print(res)
# [(1, 'LiMing', 20)]

  

posted @ 2018-10-16 16:49  寻觅beyond  阅读(17668)  评论(0编辑  收藏  举报
返回顶部