Python对MySQL数据库的操作

Python中,可以使用MySQLdb模块连接到MySQL数据库,对MySQL数据库进行操作


第一步】 MySQL安装

参考文档: http://blog.csdn.net/Jerry_1126/article/details/20837397 


第二步连接到MySQL

  • 创建数据库

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.5.19 MySQL Community Server (GPL)
mysql>

#创建数据库
mysql> create database python;
Query OK, 1 row affected (0.09 sec)

#使用数据库
mysql> use python;
Database changed

#创建表
mysql> create table people (name VARCHAR(30), age INT, sex CHAR(1));
Query OK, 0 rows affected (0.44 sec)

#插入数据
mysql> insert into people values('Tom', 20, 'M');
Query OK, 1 row affected (0.13 sec)
mysql> insert into people values('Jack', NULL, NULL);
Query OK, 1 row affected (0.06 sec)

#查看数据
mysql> select * from people;
+------+------+------+
| name | age  | sex  |
+------+------+------+
| Tom  |   20 | M    |
| Jack | NULL | NULL |
+------+------+------+
2 rows in set (0.05 sec)
  • 安装MySQLdb

官方网站: http://sourceforge.net/projects/mysql-python

下载与自己操作系统,Python版本吻合的exe文件,点击下一步即可完成安装。如下,则表示安装成功!
>>> import MySQLdb
>>> 

  • 在Python中使用MySQL

import MySQLdb                                             # 导入MySQLdb模块

db = MySQLdb.connect(host   = 'localhost',                 # 连接到数据库,服务器为本机                  
                     user   = 'root',                      # 用户名为:root
                     passwd = '1234',                      # 密码为:1234
                     db     = 'python')                    # 数据库:python
cur = db.cursor()                                          # 获得数据库游标                        

cur.execute('insert into people values("Jee", 21, "F")')   # 执行SQL,添加记录
res = cur.execute('delete from people where age=20')       # 执行SQL,删除记录   
db.commit()                                                # 提交事务

res = cur.execute('select * from people')                  # 执行SQL, 获取记录
res = cur.fetchall()                                       # 获取全部数据
print(res)                                                 # 打印数据
cur.close()                                                # 关闭游标
db.close()                                                 # 关闭数据库连接 

具体API定义,请参考:

http://blog.csdn.net/jerry_1126/article/details/40037899



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值