标题说我想做以下事情:
我在(在sql中)创建了一个表“辐射”,它是:
现在,我想从c ++能够询问用户“给一个元素”,如果用户给出例如“I”,那么例如检索“halftime”字段。
c ++代码是:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <sys/time.h>
#include <mysql/mysql.h>
using namespace std;
int main()
{
MYSQL_RES *result;
MYSQL_ROW row;
MYSQL *connection, mysql;
const char* server="127.0.0.1";
const char* user ="****";
const char* password="****";
const char* database="***";
int state;
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,server,user,password,database,0,0,0);
if (connection == NULL)
{
cout<<mysql_error(&mysql);
return 1;
}
state = mysql_query(connection, "SELECT * FROM radiation");
if (state !=0)
{
cout <<mysql_error(connection);
return 1;
}
result = mysql_store_result(connection);
row=mysql_fetch_row(result);
string name;
cout <<"\nGive the name : "<<endl;
cin >>name;
cout << "\nThe halftime for "<<name << " is "<<**row[2]**->here i want to extract the analogous filed <<" hours";
//}
mysql_free_result(result);
mysql_close(connection);
return 0;
}
我只知道sql的基础知识,我不知道上面做的有多难。
答案 0 :(得分:1)
This may help。您只需处理执行查询后得到的结果集。
res = stmt->executeQuery("SELECT * FROM radiation");
while (res->next()) {
// You can use either numeric offsets...
cout << "name_id = " << res->getInt(1); // getInt(1)/getString() returns the first column
}
答案 1 :(得分:1)
根据评论中的说明,您只需要正确构建SQL语句:
SELECT halftime FROM RADIATION WHERE name_id = 'Tc'
将结果表示为:
6
更复杂的答案:
std::string column;
std::string name;
// have the user tell you what columns are wanted
cin >> column;
// have the user give you the criteria
cin >> name;
// build the SQL
std::stringstream sql;
sql << "SELECT " << column << " FROM RADIATION WHERE name = '" << name << "'";