能连接MySQL数据库的登录程序(简化)

废话不多说直接上代码

#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来猜测是几||几的结果呢,显然不能,因为有三种情况,对吧

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值