1. 安装MySQL
使用管理员权限运行apt-get获取最新的MySQL及Python编程接口(之后用于数据库编程):
1
|
$ sudo apt-get install mysql-server python-mysqldb |
安装过程中需要输入root管理员的密码,该密码之后用于访问数据库系统。
2. 测试MySQL
通过以下命令运行MySQL的命令提示系统,并输入在安装过程中设置的密码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 47 Server version: 5.5.41-0+wheezy1 (Debian) 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. |
查看当前已建立的数据库:
1
2
3
4
5
6
7
8
9
|
mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | +--------------------+ 3 rows in set (0.00 sec) |
3. 创建一个新的数据库和表单
以上数据库都是系统建立的数据库,要想开始插入数据,首先需要建立新的数据库和表单。这里假设要实现一个CPU温度记录的功能,存放在名为"sensordb"的数据库中。使用以下命令建立数据库:
1
2
|
mysql> CREATE DATABASE sensordb; Query OK, 1 row affected (0.00 sec) |
查看数据库是否建立成功:
1
2
3
4
5
6
7
8
9
10
|
mysql> SHOW databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sensordb | +--------------------+ 4 rows in set (0.01 sec) |
在sensordb数据库下创建一个表单(table),该表单包含两个域(fields):日期和当天平均CPU温度。时间域使用的数据格式为DATE;而温度使用DECIMAL(4,1),即最大三位整数加一位小数。
1
2
3
4
5
|
mysql> USE sensordb; Database changed mysql> CREATE TABLE cputemptable(recordtime DATE, temp DECIMAL(4,1)); Query OK, 0 rows affected (0.03 sec) |
查看表单是否建立成功:
1
2
3
4
5
6
7
|
mysql> SHOW TABLES; +--------------------+ | Tables_in_sensordb | +--------------------+ | cputemptable | +--------------------+ 1 row in set (0.00 sec) |
查看表单的域名称与类型:
1
2
3
4
5
6
7
8
|
mysql> DESCRIBE cputemptable; +------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+-------+ | recordtime | date | YES | | NULL | | | temp | decimal(4,1) | YES | | NULL | | +------------+--------------+------+-----+---------+-------+ 2 rows in set (0.01 sec) |
4. 向数据库中插入测试数据
在上一步中已经成功建立了用于CPU温度采集的数据库和表单,但是因为没有任何数据,所以该表单中没有任何内容。现在通过手动插入的方式向该表单中插入若干数据,测试是否可以正常运行。
1
2
3
4
5
|
mysql> INSERT INTO cputemptable -> values('2015-03-25', 36.5); mysql> INSERT INTO cputemptable -> values('2015-03-26', 39.5); |
以上每条如果操作成功,都回返回提示:
1
|
Query OK, 1 row affected (0.00 sec) |
5. 查看数据库操作的结果
为了验证以上数据是否成功插入,可以通过select语句检索数据库:
1
2
3
4
5
6
7
8
|
mysql> SELECT * FROM cputemptable; +------------+------+ | recordtime | temp | +------------+------+ | 2015-03-25 | 36.5 | | 2015-03-26 | 39.5 | +------------+------+ 2 rows in set (0.00 sec) |
可以看到之前的两条数据已经成功插入到cputemptable数据表中。
最后使用quit退出交互系统:
1
2
|
mysql> quit Bye |