Ubuntu18.04安装和使用Mysql数据库
1、共8个命令即可完成安装
命令1
下载安装mysql的服务端:
sudo apt-get install mysql-server
命令2
切换成root用户后执行下面的命令,否则可能权限不够,想换回普通用户只需ctrl+D
sudo su -
命令3
下载安装mysql的客户端:
sudo apt-get install mysql-client
命令4
sudo apt-get install libmysqlclient-dev
命令5
安装netstat
sudo apt install net-tools
命令6
用netstat查看mysql是否安装成功
sudo netstat -tap | grep mysql
结果如下:
root@dj:~# sudo netstat -tap | grep mysql
tcp 0 0 localhost:mysql 0.0.0.0:* LISTEN 31100/mysqld
命令7
查看mysql工作状态,如果没有成功,输入命令:sudo systemctl start mysql
尝试
systemctl status mysql.service
结果如下:
root@dj:~# systemctl status mysql.service
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2020-05-01 15:06:16 CST; 2h 28min ago
Main PID: 31100 (mysqld)
Tasks: 27 (limit: 4915)
CGroup: /system.slice/mysql.service
└─31100 /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid
5月 01 15:06:15 dj systemd[1]: Starting MySQL Community Server...
5月 01 15:06:16 dj systemd[1]: Started MySQL Community Server.
命令8
mysql -u root -p #进入数据库
其中 -u 表示选择登陆的用户名,-p 表示登陆的用户密码,输入密码后就可以登录到mysql中,第一次登录,密码为空,啥都不用输入,直接回车,就好了。
结果如下:
root@dj:~# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.29-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2020, 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>
2、找回root用户的登录密码
Ubuntu在安装MySQL时会为用户创建一个debian-sys-maint
用户我们可以通过这个用户来设置
2.1 查看debian-sys-maint密码
sudo cat /etc/mysql/debian.cnf
出现以下内容,注意里面包含密码:
dj@dj:~$ sudo cat /etc/mysql/debian.cnf
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host = localhost
user = debian-sys-maint
password = WticbBDLIn7Irj3W
socket = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host = localhost
user = debian-sys-maint
password = WticbBDLIn7Irj3W
socket = /var/run/mysqld/mysqld.sock
2.2 登录debian-sys-maint用户
mysql -u debian-sys-maint -p
注意:此时密码为刚刚查到的密码
现在我们已经登录到MySQL了
2.3 设置root密码
use mysql;
update mysql.user set authentication_string=password('b307b307') where user='root' and Host ='localhost';
update user set plugin='mysql_native_password';
flush privileges;
quit;
然后重新登录:
mysql -u root -p #进入数据库
出现以下内容,表明成功登入:
dj@dj:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.7.29-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2020, 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>
OK! 问题解决了
3、卸载Mysql并重新安装
三套组合拳打完Mysql才算卸载后安装成功。
第一套组合拳: 参考
sudo apt-get remove mysql-*
dpkg -l |grep ^rc|awk '{print $2}' |sudo xargs dpkg -P
sudo apt purge mysql-server mysql-server-5.7
第二套组合拳: 参考
sudo rm /var/lib/mysql/ -R
sudo rm /etc/mysql/ -R
sudo apt-get autoremove mysql* --purge
sudo apt-get remove apparmor
第三套组合拳:重启+重新安装
reboot
sudo apt-get install mysql-server mysql-common
4、使用Python操作数据库
4.1 创建数据库和表
(1)查看已有数据库:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
(2)创建数据库:
mysql> create database pigdia; #pigdia是数据库名
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| pigdia |
| sys |
+--------------------+
5 rows in set (0.00 sec)
(3)查看指定数据库中的表:
mysql> use pigdia; #首先要选择数据库,会告诉你换好了Database changed
mysql> show tables; #查看test库下面的表,此时为空表Empty set (0.00 sec)
(4)创建表:
table1:
mysql> CREATE TABLE table1(id INT NOT NULL AUTO_INCREMENT,date DATE,pigid VARCHAR(5) NOT NULL,diarrhea VARCHAR(5) NOT NULL,fromid VARCHAR(5) NOT NULL,pic1 VARCHAR(100),pic2 VARCHAR(100),PRIMARY KEY (id))ENGINE=InnoDB DEFAULT CHARSET=utf8;
table2:
mysql> CREATE TABLE table2(id INT NOT NULL AUTO_INCREMENT,date DATE,pigid VARCHAR(5) NOT NULL,diarrhea VARCHAR(5) NOT NULL,count VARCHAR(5) NOT NULL,pic1 VARCHAR(100),pic2 VARCHAR(100),PRIMARY KEY (id))ENGINE=InnoDB DEFAULT CHARSET=utf8;
此时查看表,显示pigdia数据库中有一个表了,名叫table1:
mysql> show tables;
+------------------+
| Tables_in_pigdia |
+------------------+
| table1 |
| table2 |
+------------------+
2 rows in set (0.00 sec)
(5)查看表中的内容:
mysql> select * from table1;
mysql> select * from table2;
(6)查看表格中的段属性:
mysql> desc table1; #此时为空表
mysql> desc table2; #此时为空表
mysql> desc table1;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date | date | YES | | NULL | |
| pigid | varchar(5) | NO | | NULL | |
| diarrhea | varchar(5) | NO | | NULL | |
| fromid | varchar(5) | NO | | NULL | |
| pic1 | varchar(100) | YES | | NULL | |
| pic2 | varchar(100) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
mysql> desc table2;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date | date | YES | | NULL | |
| pigid | varchar(5) | NO | | NULL | |
| diarrhea | varchar(5) | NO | | NULL | |
| count | varchar(5) | NO | | NULL | |
| pic1 | varchar(100) | YES | | NULL | |
| pic2 | varchar(100) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
4.2 安装MySQL-python
要想使python可以操作mysql 就需要MySQL-python
驱动,它是python 操作mysql必不可少的模块。
MySQL-python-1.2.5.zip
文件下载地址:https://pypi.python.org/pypi/MySQL-python/
下载MySQL-python-1.2.5.zip
文件之后直接右键解压。进入MySQL-python-1.2.5
目录后,打开终端输入如下命令:
python2 setup.py build
sudo python2 setup.py install
测试一下看看MySQL-python是否安装成功,如果可以导入,说明成功了:
dj@dj:~$ python2
Python 2.7.17 (default, Apr 15 2020, 17:20:14)
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>>
4.3 连接数据库
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导入工具包
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect(host='localhost', user='root', password='123456', port=3306, db='pigdia', charset='utf8' )
连接数据库pigdia
使用的用户名为 root
,密码为b307b307
,此处直接使用root用户名及其密码,Mysql数据库用户授权请使用Grant命令。
4.4 数据库增删改查操作
(1)增:向数据库插入数据
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
import datetime
#获取系统日期
today=datetime.date.today()
# 打开数据库连接
db = MySQLdb.connect(host='localhost', user='root', passwd='b307b307', port=3306, db='pigdia', charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql1 = "INSERT INTO table1(date, pigid, diarrhea, fromid, pic1, pic2) \
VALUES ('%s', '%c', '%c', '%d', '%s', '%s')" % \
(today, '0', 'Y', 1, '','')
sql2 = "INSERT INTO table2(date, pigid, diarrhea, count, pic1, pic2) \
VALUES ('%s', '%c', '%c', '%d', '%s', '%s')" % \
(today, '0', 'Y', 0, '','')
try:
# 执行sql1语句
cursor.execute(sql1)
# 执行sql2语句
cursor.execute(sql2)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 关闭数据库连接
db.close()
去数据库里查询,发现确实有数据:
mysql> mysql -u root -p # 进入mysql
mysql> use pigdia; # 选择数据库
mysql> select * from table1; #显示整表信息
+----+------------+-------+----------+--------+------+------+
| id | date | pigid | diarrhea | fromid | pic1 | pic2 |
+----+------------+-------+----------+--------+------+------+
| 1 | 2020-05-02 | 0 | Y | 1 | | |
+----+------------+-------+----------+--------+------+------+
1 row in set (0.00 sec)
(2)删:从数据库删除符合条件的数据
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
import datetime
#获取系统日期
today=datetime.date.today()
# 打开数据库连接
db = MySQLdb.connect(host='localhost', user='root', passwd='b307b307', port=3306, db='pigdia', charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 删除语句
sql1 = "DELETE FROM table1 WHERE fromid = %d" % (0) #将table1中,fromid等于0的数据都删掉
try:
# 执行SQL语句
cursor.execute(sql1)
# 提交修改
db.commit()
except:
# 发生错误时回滚
db.rollback()
# 关闭数据库连接
db.close()
如果是要清空数据库:
# SQL 删除语句
sql1 = "DELETE FROM table1" #删除全表 数据
如果是要删除表1:
DROP TABLE table1 ;
(3)改:修改数据库中符合条件的数据
将 EMPLOYEE 表中的 SEX 字段为 ‘M’ 的 AGE 字段递增 1:
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
举一反三:
为了将表table2中的pigid字段为f的那条记录的count字段递增1:
sql = "UPDATE table2 SET count = count + 1 WHERE pigid = '%c'" % ('f')
(4)查:查询符合要求的数据
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
- fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
- fetchall():接收全部的返回结果行.
- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
实例:
查询EMPLOYEE表中salary(工资)字段大于1000的所有数据:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %s" % (1000)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print "fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# 关闭数据库连接
db.close()
以上脚本执行结果如下:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000