例如,如果我有一个Access Database Data.accdb,里面有2个表:Table1和Table2,我如何从Table1读取数据?我知道如何打开Sql连接。
#using <system.data.dll>
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Data::OleDb;
SqlConnection ^connection = gcnew SqlConnection(L"server=local;Trusted_Connection=yes;database=Data;");
connection->Open();
但除此之外,我不知道接下来该做什么。如何打开Table1并从中读取数据,如读取ID列?
答案 0 :(得分:1)
您可以使用OleDb来操作Access数据库。
#include <msclr\auto_handle.h>
int main(array<System::String ^> ^args)
{
using namespace System;
using namespace System::Data::OleDb;
OleDbConnection connection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\MyDatabase.accdb;Persist Security Info=False;");
connection.Open();
// Reading all records
{
msclr::auto_handle<OleDbCommand> command = connection.CreateCommand();
command->CommandText = "select * from Table1";
msclr::auto_handle<OleDbDataReader> reader = command->ExecuteReader();
while (reader->Read())
{
Console::WriteLine(
"ID={0}, DESCRIPTION={1}",
reader.get()["ID"],
reader.get()["DESCRIPTION"]);
}
}
// Insert new record
{
msclr::auto_handle<OleDbCommand> command = connection.CreateCommand();
command->CommandText = "insert into Table1 (ID, DESCRIPTION) values (3, 'THREE')";
command->ExecuteNonQuery();
}
// Changing the DESCRIPTION field for all records
{
msclr::auto_handle<OleDbCommand> selectCommand = connection.CreateCommand();
selectCommand->CommandText = "select * from Table1";
msclr::auto_handle<OleDbDataReader> reader = selectCommand->ExecuteReader();
while (reader->Read())
{
auto newDescription = reader.get()["DESCRIPTION"]->ToString();
newDescription += " - UPDATED!";
msclr::auto_handle<OleDbCommand> updateCommand = connection.CreateCommand();
updateCommand->CommandText = "update Table1 set DESCRIPTION=? where ID=?";
updateCommand->Parameters->AddWithValue("DESCRITPION", newDescription);
updateCommand->Parameters->AddWithValue("ID", reader.get()["ID"]);
updateCommand->ExecuteNonQuery();
}
}
return 0;
}