How to make an SQL query from a C/C++ application? [duplicate]
Possible Duplicate:
How to execute sql statements from a C program?
I'm creating a C applicati开发者_JAVA百科on, and i need some data from my SQL server. Does anyone know how can I make an SQL query from my C application under Windows?
Here is a code sample to start you off... Sorry I can't provide you a C example.
#include <ATLComTime.h>
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" rename("EOF", "EndOfFile")
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
int main()
{
std::string connectStr = "Provider=sqloledb;Data Source=MyDSN;Database=MyDB;User Id=DBUser;Password=Dbpwd;";
try
{
ADODB::_ConnectionPtr pConnection;
TESTHR(pConnection.CreateInstance(__uuidof(ADODB::Connection)));
ADODB::_ConnectionPtr pConnection->Open (connectStr.c_str(),"","", NULL);
VARIANT * RecordsAffected NULL;
long Options = ADODB::adExecuteNoRecords;
ADODB::_RecordsetPtr pRec = pConnection->Execute("select * from my_table",RecordsAffected,Options);
// Rest you should be able to figure out.
}
catch(_com_error &e)
{
// print error message
}
}
With C, you'll probably want to use the Microsoft ODBC API: http://msdn.microsoft.com/en-us/library/ms714562(v=VS.85).aspx
I use this heavily in my CSQLBinding class, which contains lots of usage samples. Besides the encapsulating class, (which is obviously C++ only) all of the functionality is completely compatible with plain C.
精彩评论