我正在 Visual Studio 2012 中用 C++ 构建一个项目,我首先编写了一些用于数据库访问的类。使用 SQL Server data tools我设法在我的解决方案中创建了一个 SQL 项目。
现在,我的问题是:如何使用 System::Data::SqlClient 命名空间中的类型在我的代码中连接到数据库?我得到的所有示例都使用数据库作为引用。
提前致谢
最佳答案
如果我的回答对某人有帮助,我使用了 SqlDataReader 和 SqlCommand 类来从 db.xml 中选择一些数据。请注意,我从之前创建的 App.Config (how it could be done) 中获取 ConnectionString。
SqlDataReader getSqlDataReader(String ^_sql)
{
SqlDataReader ^_sqlDataReader = nullptr;
SqlConnection ^_connection = gcnew SqlConnection();
ConnectionStringSettings ^connectionSettings = ConfigurationManager::ConnectionStrings["AppDefaultConnection"];
this->_connection->ConnectionString = connectionSettings->ConnectionString;
try {
this->_connection->Open();
}
catch (Exception ^_exception)
{
Console::WriteLine("Error : " + _exception->Message);
return nullptr;
}
try
{
SqlCommand ^_sqlCommand = gcnew SqlCommand(_sql,_connection);
_sqlDataReader = _sqlCommand->ExecuteReader();
}
catch(Exception ^_exception)
{
Console::WriteLine("Error : " + _exception->Message);
return nullptr;
}
return _sqlDataReader;
}
为了正确构建 SQL,我们应该知道类 SqlParameter (example for C#) 并避免 SQL 注入(inject)攻击。
要使用 getSqlDataReader 函数:
SqlDataReader ^reader = getSqlDataReader(yourParameterizedQueryString);
List<TypeToFetch>^ data = gcnew List<TypeToFetch^>();
if(reader != nullptr && reader->HasRows)
{
TypeToFetch^ typeToFetch = gcnew TypeToFetch();
while(reader->Read())
{
// example
TypeToFetch->id = (int) reader["Id"];
TypeToFetch->name = reader["Name"]->ToString();
data->Add(typeToFetch);
}
}
This question/answer可以帮助插入。
关于c++ - 使用 SqlConnection 在托管 C++ 中连接和查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22959665/