一, 127.0.0.1和localhost连接mysql数据库的区别
1, localhost连接mysql数据库情况
mysql -h localhost -uroot -p
2, 下面是127.0.0.1连接mysql数据库的情况
mysql -h 127.0.0.1 root -p
不知道你看出连接的方式不同下面我就分析一下
localhost是通过UNIX的socket本地连接而没有通过端口3306, 127.0.0.1是通过TCP的协议连接3306的端口 其中的关系就是我想你也知道吧
查看端口的命令:
lsof -i:3306
其实UNIX的本地通信在系统中服务非常频繁 比如双进程守护(杀不死进程) ,在android系统也应用了,
下面是连接mysql数据库的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include <unistd.h>
#define _USER_ "root" //用户名
#define _HOST_ "localhost" //host
#define _PASSWD_ "root" //root 用户名密码
#define _DB_ "DB" //库名
#define _PORT_ 3306 //port
#define _UNIX_SOCK_ "/var/lib/mysql/mysql.sock"
int main(int argc, char *argv[])
{
int ret, i;
MYSQL *mysql;
MYSQL_RES * res;
char strsql[512] = { 0};
//1,mysql_init 初始化
mysql = mysql_init(NULL);
if (mysql == NULL) {
printf("mysql_init error\n");
return -1;
}
//2,mysql_real_connect链接
mysql = mysql_real_connect(mysql,
_HOST_,
_USER_,
_PASSWD_,
_DB_,
0,
_UNIX_SOCK_, // UNIX的本地通信的配置默认位置/var/lib/mysql/mysql.sock
0);
if (mysql == NULL) {
printf("mysql_real_connect error\n");
return -1;
}
printf("connect mysql ok\n");
static int p = 0;
while (1) {
printf("sleep\n");
sleep(10);
++p;
if (p == 4)
break;
}
//关闭mysql
mysql_close(mysql);
return 0;
}
二, 聊聊mysql的配置文件my.conf
我昨天和同事遇到的问题 , 我们要移动mysql的默认保存数据库的文件的位置, 但是我了, 又改变本地连接的配置 就是UNIX的socket连接 所以我们使用代码localhost连接不上mysql数据库是因为mysql数据库的api函数mysql_real_connect默认的位置是/var/lib/mysql/mysql.sock的位置
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html
[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
# mysql数据库的库的保存位置设置
datadir=/var/lib/mysql
# mysql数据库连接localhost使用本地UNXI本地socket连接文件位置设置
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Recommended in standard MySQL setup
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
nice = 0
#pid-file=/var/lib/mysql/mysql.sock
#设置编码utf-8
[mysql]
default-character-set =utf8