瑞典MySQL AB公司开发,由SUN收购,而后SUN被甲骨文并购,目前属于Oracle公司。MySQL是一种关联数据库管理系统,由于其体积小、速度快、总体拥有成本低,目前被大量的公司所使用。MySQL软件采用了双授权政策,分为社区版和企业版。
使用sudo apt安装Mysql
sudo apt install mysql-server-8.0
Ubuntu下安装mysql8.0之后,默认root用户是没有密码的,可以使用如下命令直接进入MySQL
sudo mysql -uroot
设置root密码
mysql> use mysql; mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密码'; mysql>flush privileges; mysql> quit;
重启MySQL服务
sudo systemctl restart mysql.service
完成上面的步骤之后,就可以使用下面的命令来登录MySQL
sudo mysql -uroot -p
备注:头文件路径 /usr/include/mysql/
库文件路径:/usr/lib/x86_64-linux-gnu/
Mysql启动、关闭、重启
// 启动MySQL service mysqld start // 停止MySQL service mysqld stop // 重启MySQL service mysqld restart // 查看MySQL运行状态 systemctl status mysql.service
安装mysql客户端
sudo apt install libmysqlclient-dev
首先在终端中查看MySQL的依赖项
dpkg --list|grep mysql
卸载mysql-common
sudo apt-get remove mysql-common
卸载mysql-server-8.0
sudo apt-get autoremove --purge mysql-server-8.0
清除残留数据
dpkg -l|grep ^rc|awk '{print$2}'|sudo xargs dpkg -P
再次查看MySQL的剩余依赖项
dpkg --list|grep mysql
继续删除剩余依赖项
sudo apt-get autoremove --purge mysql-apt-config
至此已经没有了MySQL的依赖项,彻底删除
创建数据库:create database school;
使用数据库:use school;
创建学生表:
create table student( id int, name varchar(20), chinese int, english int, math int );
插入数据
insert into student(id,name,chinese,english,math) values(1, '范建',80,85,90); insert into student(id,name,chinese,english,math) values(2,'罗况',90,95,95); insert into student(id,name,chinese,english,math) values(3,'杜子腾',80,96,96); insert into student(id,name,chinese,english,math) values(4,'范冰',81,97,85); insert into student(id,name,chinese,english,math) values(5,'申晶冰',85,84,90); insert into student(id,name,chinese,english,math) values(6,'郝丽海',92,85,87); insert into student(id,name,chinese,english,math) values(7,'郭迪辉',75,81,80); insert into student(id,name,chinese,english,math) values(8,'张飞',77,80,79); insert into student(id,name,chinese,english,math) values(9,'任我行',95,85,85); insert into student(id,name,chinese,english,math) values(10,'史泰香',94,85,84);
编写如下测试程序
#include <iostream> #include "mysql/mysql.h" int main() { const char* host="127.0.0.1"; const char* user="root"; const char* passwd="xxxxxx"; const char* db="school"; unsigned int port=3306; MYSQL *mysql=mysql_init(NULL); mysql=mysql_real_connect(mysql, host, user, passwd, db, port, nullptr, 0); const char* sql="select * from student"; int ret=mysql_query(mysql, sql); MYSQL_RES* result=mysql_store_result(mysql); MYSQL_ROW row=nullptr; while(row=mysql_fetch_row(result)) { std::string s; int num=mysql_field_count(mysql); for(int i=0;i<num-1;i++) { s=s+row[i]+"\t"; } s+=row[num-1]; std::cout<<s<<std::endl; } mysql_free_result(result); mysql_close(mysql); return 0; }
编译需要链接libmysqlclient库
g++ main.cpp -o main -lmysqlclient