废话不多说直接上代码
#include <iostream>
#include <mysql.h>
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main() {
sql::mysql::MySQL_Driver *driver;
sql::Connection *connection;
sql::Statement *statement;
sql::ResultSet *resultSet;
// 创建数据库连接
driver = sql::mysql::get_mysql_driver_instance();
connection = driver->connect("tcp://127.0.0.1:3306", "<username>", "<password>"); // 替换为你的数据库用户名和密码
connection->setSchema("<database_name>"); // 替换为你的数据库名称
string username, password;
cout << "请输入用户名:";
cin >> username;
cout << "请输入密码:";
cin >> password;
// 执行登录查询
statement = connection->createStatement();
resultSet = statement->executeQuery("SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'");
// 检查查询结果
if (resultSet->next()) {
cout << "登录成功!" << endl;
} else {
cout << "登录失败!" << endl;
}
// 释放资源
delete resultSet;
delete statement;
delete connection;
return 0;
}
这里我将登录程序极度简化,只有两种情况,一个成功一个失败。
我用了MySQL Connector/C++库来实现连接MySQL数据库,你最后还是要把mysql的账号和密码填进去的,这里我用<username>和<password>来代替。
*注意:这个代码只是一个简单的样例,可能会存在安全问题,请你根据自己的需求和实际情况进行适当的改进和安全性处理。
当然我这里也可以提供一个加密的样例:
#include <iostream>
#include <openssl/sha.h>
#include <cstring>
std::string sha256(const std::string &password) {
unsigned char hash[SHA256_DIGEST_LENGTH];
char hash_hex[SHA256_DIGEST_LENGTH * 2 + 1];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, password.c_str(), password.length());
SHA256_Final(hash, &sha256);
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
sprintf(&hash_hex[i * 2], "%02x", hash[i]);
}
return std::string(hash_hex);
}
int main() {
std::string password;
std::cout << "请输入密码:";
std::getline(std::cin, password);
std::string hashedPassword = sha256(password);
std::cout << "密码的SHA-256哈希值为:" << hashedPassword << std::endl;
return 0;
}
只需要把主程序内容修改成你想要实现的内容即可。
*这里给没接触过加密算法的人科普一下:sha256属于费堆成加密算法,是无法通过哈希值来还原原味的,毕竟在运算过程中,信息损失掉了,打个最简单的比方,1||1=1没错吧,那你能通过结果1来猜测是几||几的结果呢,显然不能,因为有三种情况,对吧