您的位置:首页 > 编程语言 > Python开发

ubuntu12.04.4下MySQLdb-python的使用

2014-04-13 18:11 513 查看
1. MySQLdb-python的安装:/article/8659025.html

2. 进入mysql控制台/创建数据库/使用数据库/创建表/插入记录/查看表中的内容/退出mysql控制台:

cryhelyxx@ada:~$ mysql --user=root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.17 MySQL Community Server (GPL)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database python;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database   |
+--------------------+
| information_schema |
| mysql  |
| performance_schema |
| python |
| test   |
+--------------------+
5 rows in set (0.02 sec)

mysql> use python;
Database changed
mysql> CREATE TABLE people(name VARCHAR(30), age INT, sex CHAR(1));
Query OK, 0 rows affected (0.58 sec)

mysql> INSERT INTO people VALUES('Cryhelyxx', 22, 'M');
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM people;
+-----------+------+------+
| name  | age  | sex  |
+-----------+------+------+
| Cryhelyxx |   22 | M|
+-----------+------+------+
1 row in set (0.00 sec)

mysql> exit
Bye
cryhelyxx@ada:~$

3. 在python中使用mysql数据库:

以下是一个PyMySQL.py文件, 用来测试python操作mysql数据库:

#-*- coding: utf-8 -*-
#file: PyMySQL.py

import MySQLdb  #导入MySQLdb模块
conn = MySQLdb.connect(
host = 'localhost', #连接到数据库, 服务器为本机
user = 'root',  #用户名为root
passwd = 'admin',   #密码为admin
db = 'python',  #数据库名为python
unix_socket = '/tmp/mysql.sock')   #指定Unix socket的位置
cur = conn.cursor()   #获取数据库游标
cur.execute('insert into people(name, age, sex) values(\'Jee\', 21, \'F\')')#执行SQL语句, 添加记录
conn.commit()   #提交事务
r = cur.execute('SELECT * FROM people') #执行SQL语句, 获取记录
r = cur.fetchall()  #获取数据
print r #输入数据
cur.close() #关闭游标
conn.close()#关闭数据库

执行命令运行PyMySQL.py, 如下:

cryhelyxx@ada:~/python$ python PyMySQL.py
(('Cryhelyxx', 22L, 'M'), ('Jee', 21L, 'F'))

4. 继续补充中...



更多内容参见Python在线帮助文档
>>>help()
help>MySQLdb
更多MySQLdb-python属性/方法/参数等内容参见:http://mysql-python.sourceforge.net/MySQLdb.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: