Question

I'm building a project in C++ in Visual Studio 2012 and I've started by writing some classes for database access. Using SQL Server data tools I've managed to create a SQL project in my solution.

Now, my question is: How can I use the types in System::Data::SqlClient namespace to connect to the database in my code? All the examples I get are using the database as reference.

Thanks in advance

Was it helpful?

Solution

If my answer helps someone, I have used the classes SqlDataReader and SqlCommand in order to select some data from db. Note that I'm fetching the ConnectionString from an App.Config I've created earlier (how it could be done).

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;
}

To proper build the SQL we should be aware of the class SqlParameter (example for C#) and avoid SQL injection attacks.

To use the getSqlDataReader function:

   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 can help on INSERT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top