0

I have the following code:

void get_id(int i, std::vector<item>& _items) {

    auto cpool = get_db_connection_pool();
    auto con = cpool->get_connection();
    db::result m;

    int _id;

    if (i == 1) {               

        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE1                    
        )***";

        db::statement st(con, sql);

        m = st.execute().into(_id);

        while (m.move_next()) {                 
            _items.push_back(item {_id});
        }
    }
    else {
        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE2                    
        )***";

        db::statement st(con, sql);

        m = st.execute().into(_id);

        while (m.move_next()) {                 
            _items.push_back(item {_id});
        }
    }
}

As you can see the code

        db::statement st(con, sql);

        m = st.execute().into(_id);

        while (m.move_next()) {                 
            _items.push_back(item {_id});
        }

is written duplicated in the if-else statement. I would like to move that part outside of the if else case like this:

void get_id(int i, std::vector<item>& _items) {

    auto cpool = get_db_connection_pool();
    auto con = cpool->get_connection();
    db::result m;

    int _id;

    if (i == 1) {               

        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE1                    
        )***";
    }
    else {
        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE2                    
        )***";
    }


    db::statement st(con, sql);

    m = st.execute().into(_id);

    while (m.move_next()) {                 
        _items.push_back(item {_id});
    }
}

I've tried replacing sql[] in the if-else case with a temporary std::wstring but I can't figure out how to cast std::wstring to const wchar_t sql[].

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
President Camacho
  • 1,860
  • 6
  • 27
  • 44

1 Answers1

3

std::wstring has a member function c_str that will return a const wchar_t* to the underlying string. As long as db::statement takes a const wchar_t [] or const wchar_t * then you can use

std::wstring sql;
if (i == 1) {               

    sql = LR"***(
        SELECT * FROM TABLE1                    
    )***";
}
else {
    sql = LR"***(
        SELECT * FROM TABLE2                    
    )***";
}

db::statement st(con, sql.c_str());
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Thanks, I know of c_str() but didnt think of doing it like that. Thanks! Do you know a site where I can read about c++ types? I'm new in the c++ game my knowledge is mostly in c# – President Camacho Apr 05 '16 at 06:32
  • @PresidentCamacho I use [cppreference.com](http://en.cppreference.com/w/) quite a bit. You may also want to get a nice [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Apr 05 '16 at 11:46