python的mysql模块_python使用MySQLdb模块连接MySQL
1.安装驱动
目前有两个MySQL的驱动,我们可以选择其中一个进行安装:
MySQL-python:是封装了MySQL C驱动的Python驱动;mysql-connector-python:是MySQL官方的纯Python驱动。
MySQL-python:
mysql-connector-python:
2.测试连接
这里使用MySQL-python驱动,即MySQLdb模块。
test_connect.py
1 #!/usr/bin/python
2 #-*- coding: UTF-8 -*-
3
4 importMySQLdb5
6 #打开数据库连接
7 db = MySQLdb.connect("localhost", "root", "123456", "test")8
9 #使用cursor()方法获取操作游标
10 cursor =db.cursor()11
12 #使用execute方法执行SQL语句
13 cursor.execute("SELECT VERSION()")14
15 #使用 fetchone() 方法获取一条数据库。
16 data =cursor.fetchone()17
18 print "Database version : %s" %data19
20 #关闭数据库连接
21 db.close()
测试结果如下,连接成功:
3.创建数据库表
测试成功后,我们可以在python中直接为MySQL创建表:
create_table.py
1 #!/usr/bin/python
2 #-*- coding: UTF-8 -*-
3
4 importMySQLdb5
6 #打开数据库连接
7 db = MySQLdb.connect("localhost", "root", "123456", "test")8
9 #使用cursor()方法获取操作游标
10 cursor =db.cursor()11
12 #如果数据表已经存在使用 execute() 方法删除表。
13 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")14
15 #创建数据表SQL语句
16 sql = """CREATE TABLE EMPLOYEE (17 FIRST_NAME CHAR(20) NOT NULL,18 LAST_NAME CHAR(20),19 AGE INT,20 SEX CHAR(1),21 INCOME FLOAT )"""
22
23 cursor.execute(sql)24
25 #关闭数据库连接
26 db.close()
建表结果 如下:
4.操作数据库表
注意点:MySQL中的占位符为%s
operate_table.js
1 #!/usr/bin/python
2 #-*- coding: UTF-8 -*-
3
4 importMySQLdb5
6 #打开数据库连接
7 db = MySQLdb.connect("localhost", "root", "123456", "test")8
9 #使用cursor()方法获取操作游标
10 cursor =db.cursor()11
12 #SQL插入语句
13 ins_sql = """INSERT INTO EMPLOYEE(FIRST_NAME,14 LAST_NAME, AGE, SEX, INCOME)15 VALUES ('yu', 'jie', 20, 'M', 8000)"""
16
17 ins_sql1 = 'insert into employee(first_name, last_name, age, sex, income) values (%s, %s, %s, %s, %s)'
18
19 #SQL查询语句
20 sel_sql = 'select * from employee where first_name = %s'
21
22 #SQL更新语句
23 upd_sql = 'update employee set age = %s where sex = %s'
24
25 #SQL删除语句
26 del_sql = 'delete from employee where first_name = %s'
27
28 try:29 #执行sql语句
30 #insert
31 cursor.execute(ins_sql)32 cursor.execute(ins_sql1, ('xu', 'f', 20, 'M', 8000))33 #select
34 cursor.execute(sel_sql, ('yu',))35 values =cursor.fetchall()36 printvalues37 #update
38 cursor.execute(upd_sql, (24, 'M',))39 #delete
40 cursor.execute(del_sql, ('xu',))41
42 #提交到数据库执行
43 db.commit()44 except:45 #发生错误时回滚
46 db.rollback()47
48 #关闭数据库连接
49 db.close()
执行插入操作
执行查询操作
执行更新操作
执行删除操作
查询语句的知识点:
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
fetchall():接收全部的返回结果行.
例如该例子:
1 sel_sql = 'select * from employee where first_name = %s'
2 cursor.execute(sel_sql, ('yu',))3 results =cursor.fetchall()4 for row inresults:5 fname =row[0]6 lname = row[1]7 age = row[2]8 sex = row[3]9 income = row[4]10 print "fname=%s, lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income)
结果如下:
总结
以上是生活随笔为你收集整理的python的mysql模块_python使用MySQLdb模块连接MySQL的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: java 计算两个日期之间的天数_Jav
- 下一篇: postman 安装失败_【Postma