c++ - 使用 SqlConnection 在托管 C++ 中连接和查询数据库

标签 c++ sql visual-studio-2012 sqlconnection

我正在 Visual Studio 2012 中用 C++ 构建一个项目,我首先编写了一些用于数据库访问的类。使用 SQL Server data tools我设法在我的解决方案中创建了一个 SQL 项目。

现在,我的问题是:如何使用 System::Data::SqlClient 命名空间中的类型在我的代码中连接到数据库?我得到的所有示例都使用数据库作为引用。

提前致谢

最佳答案

如果我的回答对某人有帮助,我使用了 SqlDataReader 和 SqlCommand 类来从 db.xml 中选择一些数据。请注意,我从之前创建的 App.Config (how it could be done) 中获取 ConnectionString。

SqlDataReader getSqlDataReader(String ^_sql)
{
    SqlDataReader ^_sqlDataReader = nullptr;

    SqlConnection ^_connection = gcnew SqlConnection();

    ConnectionStringSettings ^connectionSettings = ConfigurationManager::ConnectionStrings["AppDefaultConnection"];
    this->_connection->ConnectionString = connectionSettings->ConnectionString;

    try {
        this->_connection->Open();
    } 

    catch (Exception ^_exception)
    {
        Console::WriteLine("Error : "  + _exception->Message);
        return nullptr;
    }

    try
    {
        SqlCommand ^_sqlCommand = gcnew SqlCommand(_sql,_connection);
        _sqlDataReader = _sqlCommand->ExecuteReader();
    }

    catch(Exception ^_exception)
    {
        Console::WriteLine("Error : "  + _exception->Message);
        return nullptr;
    }

    return _sqlDataReader;
}

为了正确构建 SQL,我们应该知道类 SqlParameter (example for C#) 并避免 SQL 注入(inject)攻击。

要使用 getSqlDataReader 函数:
   SqlDataReader ^reader = getSqlDataReader(yourParameterizedQueryString);

        List<TypeToFetch>^ data = gcnew List<TypeToFetch^>();
        if(reader != nullptr && reader->HasRows)
        {
            TypeToFetch^ typeToFetch = gcnew TypeToFetch();
            while(reader->Read())
            {
                    // example
                TypeToFetch->id = (int) reader["Id"];
                TypeToFetch->name = reader["Name"]->ToString();
                data->Add(typeToFetch);
            }
        }

This question/answer可以帮助插入。

关于c++ - 使用 SqlConnection 在托管 C++ 中连接和查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22959665/

相关文章:

sql - 参数异常 : Keyword not supported: 'server'

mysql - SQL - 如何为我的选择查询添加此自定义订单?

asp.net-mvc-3 - 如何在 MVC3 的 Razor View 编辑器中获取折叠 + 和 - 符号

visual-studio-2012 - 将 TF.exe 与 Team Foundation Service 一起使用?

c++ - 具有引用模板参数的函数模板

c++ - Libtorrent 设置枚举

mysql - 在同一个表中选择多个条件

visual-studio-2012 - 在Windows Phone 8.0应用程序中选择手机而不是耳机的麦克风

c++ - 如何将可变数量的参数从一个函数传递到另一个函数?

c++ - 尝试动态增加数组大小