文章目录


推荐指数:⭐⭐⭐⭐⭐

数据库安装命令

sudo apt-get install mysql-server mysql-client

如果遇到找不到包,尝试更新

sudo apt-get update

再次执行数据库安装命令之后还是找不到包,更新软件源

sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak   #备份源
sudo gedit sources.list #编辑源

​清华镜像源​​​各个版本的都有:​​https://mirror.tuna.tsinghua.edu.cn/help/ubuntu/​

或者将source.list文件内容替换成下面的

deb http://mirrors.aliyun.com/ubuntu/ trusty main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ trusty-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ trusty-backports main restricted universe multiverse

更新

sudo apt-get update #更新
sudo apt-get install mysql-server mysql-client #安装数据库

安装完成之后要你输入root密码两次,密码要记住呀

查看数据库是否安装

netstat -tap|grep mysql   #有结果就说明数据库已经启动了

登录数据库

mysql -h localhost -P 3306 -u root -p #本地数据库连接
#输入刚刚设置的密码
mysql -h 122.112.174.128 -P 3306 -u db_student -p #远程登录

用C编译mysql数据库时,报错

fatal error: mysql.h: No such file or directory

出现这个错误是因为体系没有安装mysql开发库

执行下面指令安装

sudo apt-get install libmysql++-dev

编译时须要加连接-lmysqlclient.

C语言连接mysql数据库Demo

登录数据库

mysql -h localhost -P 3306 -u root -p
Enter password:

查看数据库

mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| deroy |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)

创建数据库

// 建立yourdb库
create database yourdb;

// 创建user表
USE yourdb;
CREATE TABLE user(
username char(50) NULL,
password char(50) NULL
)ENGINE=InnoDB;

// 添加数据
INSERT INTO user(username, password) VALUES('name', 'password');

C语言连接数据库

#include <stdio.h>
#include <mysql/mysql.h>

int main()
{
MYSQL mysql;
int t, r;
/*连接之前,先用mysql_init初始化MYSQL连接句柄*/
mysql_init(&mysql);
/*使用mysql_real_connect连接服务器,其参数依次为MYSQL句柄,服务器IP地址,
登录mysql的用户名,密码,要连接的数据库等*/
if (!mysql_real_connect(&mysql, "localhost", "root", "123456", "yourdb", 0, NULL, 0))
printf("Error connecting to Mysql!\n");
else
printf("Connected Mysql successful!\n");

/*关闭连接*/
mysql_close(&mysql);
return 0;
}
g++ -I/usr/include/mysql main.cpp -L/usr/lib/mysql -lmysqlclient -o csql_demo.e
./csql_demo.e 
Connected Mysql successful!