C ++ / CLI中的SQL Prepared语句参数

时间:2018-04-02 09:45:39

标签: mysql .net winforms c++-cli

我正在Visual Studio 2017中进行C ++ / CLI winform。

此应用程序通过从派生类调用基类方法从数据池插入mysql数据库。因为数据可能包含撇号所以我将使用预处理语句来处理它。

以下是代码的一部分:

void SQLconn::insertData(string topic, string comment, string date) {
string sql = "INSERT INTO data(Topics, Comments, DateTime) VALUES (@topic, @comment, @date)";

MySqlConnection^ conn = gcnew MySqlConnection(connectionInfo);
conn->Open()
MySqlDataReader^ dataReader;
MySqlCommand^ MyCommand2 = gcnew MySqlCommand(gcnew String(sql.c_str()), conn);

//error incurs here
MyCommand2->Parameters->AddWithValue("@topic", topic);
MyCommand2->Parameters->AddWithValue("@comment", comment);
MyCommand2->Parameters->AddWithValue("@date", date);

dataReader = MyCommand2->ExecuteReader();
this->dataReader->Close();

}

一切都很好但是,我在参数声明中收到错误。

C2664: 'MySql::Data::MySqlClient::MySqlParameter ^MySql::Data::MySqlClient::MySqlParameterCollection::AddWithValue(System::String ^,System::Object ^)': cannot convert argument 2 from 'std::string' to 'System::Object ^'
function "MySql::Data::MySqlClient::MySqlParameterCollection::AddWithValue" cannot be called with the given argument list

我的问题是,这是否是实施准备好的陈述的正确方法,还是可以这样做?

更新, 我尝试以下,

MySqlParameter^ pstmt;
pstmt = gcnew MySqlParameter("@topic", MySqlDbType.Varchar);

没有工作=(

1 个答案:

答案 0 :(得分:2)

It works now with this conversion of data type

MyCommand2->Parameters->AddWithValue(gcnew String("@topic"), gcnew String(topic.c_str()));
MyCommand2->Parameters->AddWithValue(gcnew String("@comment"), gcnew String(comment.c_str()));
MyCommand2->Parameters->AddWithValue(gcnew String("@date"), gcnew String(date.c_str()));