Home My program reads 0 from the database even though there is a 1
Reply: 1

My program reads 0 from the database even though there is a 1

Yoo
1#
Yoo Published in 2018-01-13 00:00:09Z

I don't understand whats wrong with the code, I have read a lot of times but I can't find the error

pstmt = con->prepareStatement("SELECT (?) FROM votos WHERE id = (?)");
pstmt->setString(1, eleccion);
pstmt->setInt(2, p->getId());
res = pstmt->executeQuery();
while(res->next())
{
    p->setVoto(res->getInt(1));
}

When the eleccion and id variables are Provincial and 1 respectively the getInt(1) function should return 1, but it returns 0.

The command (in the mysql command line):

SELECT Provincial from Votos WHERE id=1

Returns a table with one row and one column with the value 1

Side notes:

Spelling was checked

The getId() function works correctly

The compiler doesn't give any error

Barmar
2#
Barmar Reply to 2018-01-13 17:05:49Z

You can't use a placeholder in a prepared query for a column name. It's returning the value of the string eleccion, not using it as the name of a column in the table. You need to do string concatenation to substitute the column name.

std::string sql = std::string("SELECT `") + eleccion + "` FROM votos WHERE id = ?";
pstmt = con->prepareStatement(sql.c_str());
pstmt->setInt(1, p->getId());
res = pstmt->executeQuery();
while(res->next())
{
    p->setVoto(res->getInt(1));
}

If the value of eleccion is coming from the user or some other untrusted source, make sure you validate it before concatenating, to prevent SQL injection.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.371238 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO