下面先给出MySQL连接前的官方文档
Application programs should use this general outline for interacting with MySQL:
1. Initialize the MySQL library by calling mysql_library_init(). This function exists in both the libmysqlclient C client library and the libmysqldembedded server library, so it is used whether you build a regular client program by linking with the -libmysqlclient flag, or an embedded server application by linking with the -libmysqld flag.
2. Initialize a connection handler by calling mysql_init() and connect to the server by calling mysql_real_connect().
3.Issue SQL statements and process their results. (The following discussion provides more information about how to do this.)
4.Close the connection to the MySQL server by calling mysql_close().
5.End use of the MySQL library by calling mysql_library_end().
可能有朋友会问,为什么要这么怎么做,为什么要做这么多步骤。
我给出的答案是,用某个东西就是更具官方给出的规则进行使用,可以不必知道为什么要这么做,但必须要遵守规则。
由此我们易知首先得mysql_library_init()
然后mysql_init()和mysql_real_connect();
最后为mysql_close()和mysql_library_end();
下面是代码
#include<stdio.h>
#include<stdlib.h>
#include<WinSock2.h>
#include<mysql.h>
#pragma comment(lib, "libmysql")
int main()
{
if (mysql_library_init(0, NULL, NULL))
{
printf_s("could not initialize MySQL library\n");
getchar();
exit(1);
}
MYSQL conn;
mysql_init(&conn);
MYSQL *ret = mysql_real_connect(&conn, "127.0.0.1", "root", "123456", "demo", 0, NULL, 0);
if (!ret)
{
printf_s("Failed to connect to database: %s\n", mysql_error(&conn));
getchar();
exit(1);
}
printf_s("successful database connection\n");
mysql_close(&conn);
mysql_library_end();
getchar();
return 0;
}
运行结果如下:
但我们进入debug目录,可以看到exe文件,我们打开他,直接对字符串进行搜索,可以得到如下图所示类容
这是非常不安全的。
虽然,当任意用户登录数据库时无需检验(这些帐号和密码是可以暴露的)
但我觉得这是一个有瑕疵的,所以我们对他进行简单加密。
如下代码所示:
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <mysql.h>
#pragma comment(lib, "libmysql")
//简单加密
char* encrypt(char *Code, int Judge)
{
int CodeLen = strlen(Code);
//1为ip地址解密
if (Judge == 1)
{
for (int i = 0; i < CodeLen; i++)
{
if (i == 3 || i == 5 || i == 7)
continue;
Code[i] -= 2;
}
}
//用户名解密
else if (Judge == 2)
{
for (int i = 0; i < CodeLen; i++)
Code[i] -= 3;
}
//密码解密
else if (Judge == 3)
{
for (int i = 0; i < CodeLen; i++)
Code[i] -= 1;
}
//表名加密
else
{
for (int i = 0; i < CodeLen; i++)
Code[i] -= 1;
}
return Code;
}
int main()
{
char host[10] = "349.2.2.3";
char user[5] = "urrw";
char passwd[7] = "234567";
char db[5] = "efnp";
if (mysql_library_init(0, NULL, NULL))
{
printf("could not initialize mysql library\n");
exit(1);
};
MYSQL conn;
mysql_init(&conn);
MYSQL* ret = mysql_real_connect(&conn, encrypt(host, 1), encrypt(user, 2), encrypt(passwd, 3), encrypt(db, 4), 0, NULL, 0);
if (!ret)
{
printf_s("failed to connect to database: %s\n",
mysql_error(&conn));
}
printf_s("successful database connection\n");
mysql_close(&conn);
mysql_library_end();
getchar();
return 0;
}
运行结果如下:
现在我们打开exe文件,看看他所处的字符串的地方变成了什么值
如下图所示: