简体   繁体   中英

Passing argument into const char *

I want to make mysql query it look like this:

SELECT name FROM AUTHORS where name LIKE %[here argument]%

I search for solution and i find putting arg in "+[arg]+" like this;

  const char * author = getString("Author: ", 100).c_str();
  // res type MYSQL_RES* res
  res = exec_query(conn, "select name from authors where name like '%"+author+"%'");

But i gives me an error:

expression must have integral or unscoped enum type

You have two problems with your code:

  • you are storing a dangling pointer in author

  • you are trying to concatenate multiple const char* pointers.

Change your code to treat author and your concatenated SQL as std::string instead. You can use std::string::c_str() when passing the final SQL string to mysql, eg:

std::string author = getString("Author: ", 100);
// res type MYSQL_RES* res
std::string sql = "select name from authors where name like '%"+author+"%'";
res = exec_query(conn, sql.c_str());

Do be aware that the code above is subject to SQL Injection attacks. You really should be using a parameterized query instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM