Search code examples
sqlc++-cli

How can I get an int from a database using clr/c++ and convert it into a system::int


The problem that I am having is that I want to read an integer value from a database but I need to do CLR conversions to do this as it needs to be appended onto another integer from my database and then written back into the database. I have already done string conversions in this project so I do not see why I cannot do integer.

Code I already have:

try
        {
            OleDbDataReader^ reader = testData.openData(fieldEntity, field, tableName);
            while (reader->Read())
            {
                string userName, passWord;
                String^ username = reader["username"]->ToString();
                String^ password = reader["password"]->ToString();
                stringConversion(username, userName);
                stringConversion(password, passWord);
                /* this means that i will have the System::String^ as system::string and I want the same as this but for integers not strings*/
            }
         }

stringConversion

void stringConversion(String ^ s, string& os)
{
    using namespace Runtime::InteropServices;
    const char* chars =
        (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
    os = chars;
    Marshal::FreeHGlobal(IntPtr((void*)chars));
}

Edit: my catch statement is missing but it doesn't need to be there.


Solution

  • I have found a solution to this problem and it is actually rather basic.

    When dealing with an object I can just cast it in the same way I would a normal variable.

    For example,

        OleDbDataReader^ reader = testData.openData(fieldEntity, field, tableName);
            while (reader ->Read())
            {
                Object^ healthptr = reader["Health"];
                health = (int)healthptr;
            }