gpt4 book ai didi

winforms - 在 Visual C++ 中检查 MySql 连接是否打开

转载 作者:行者123 更新时间:2023-11-30 00:24:46 25 4
gpt4 key购买 nike

抱歉,如果您感到无聊。我在几个搜索引擎上进行了搜索,但没有得到任何结果。无论如何,我正在一个数据库是 mysql 的应用程序中工作。现在我已经创建了一个数据库包装类,并想检查连接是否已打开。你能帮我吗?

             String^ constring = L"datasource=localhost;port=3306;username=root;password=pass;database=eps;";
String^ my_query = L"select id from eps_users where usr = '" + this->user_name->Text + "' and psw = md5('" + this->pass_word->Text + "');";
MySqlConnection^ conDatabase = gcnew MySqlConnection(constring);
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
MySqlDataReader^ myreader;
try
{
conDatabase->Open();
myreader = cmd->ExecuteReader();
int count = 0;
while (myreader->Read())
{
count = count + 1;

}
if (count == 1){
MessageBox::Show("Username And Password is correct.", "Success", MessageBoxButtons::OK,
MessageBoxIcon::Information);
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
}
else{
MessageBox::Show("Username And Password is not correct.", "Error", MessageBoxButtons::OK,
MessageBoxIcon::Error);
// <del>
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
// </del>
}
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
conDatabase->Close();

我需要检查 if( conDatabase->HasBeenOpened()) { conDatabase->Open();}

最佳答案

MySqlConnection 类型实现了一种称为连接池的功能,该功能依赖于垃圾收集器来帮助回收与数据库的连接,因此连接对象的最佳实践是为大多数数据库调用创建一个全新的对象,以便垃圾收集器能够正确回收旧的。过程是这样的:

  1. 创建新连接
  2. 打开连接
  3. 将连接用于一项查询/事务
  4. 释放连接

所有四个步骤都位于一个 try/catch/finally block 中。 (此外,处置步骤需要在finally block 内进行!)因为您通常从一个全新的连接对象开始,所以通常不需要先检查它是否打开:您知道它已关闭。您也不需要在调用 Open() 后检查状态:该方法将阻塞直到完成,如果失败则抛出异常。

但是,如果您确实处于一种(罕见!)情况,最好长时间保持连接,则可以像这样检查状态:

if( conDatabase->State == ConnectionState::Open)
<小时/>

现在,我想谈谈该代码中的另一个问题。问题归结为:如果我将以下内容放入您的用户名文本框中,您认为会发生什么:

';DROP Table eps_users;--

If you think that it will try to execute that DROP statement in your database, you're right: it will! More subtle and damaging queries are possible, as well. This is a huge issue: there are bots that run full time crawling web sites looking for ways to abuse this, and even an corporate internal desktop apps will get caught from time to time. To fix this, you need to use Parameterized Queries for every instance where include user-provided data as part of your sql statement.

A quick example might look like this:

String^ my_query = L"select id from eps_users where usr = @userID;";
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
cmd->Parameters->AddWithValue(L"@userID", this->user_name->Text);

关于winforms - 在 Visual C++ 中检查 MySql 连接是否打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22974233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com