473,322 Members | 1,405 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Using MS SQL from C++ guidelines

Hi all,

Where can I find guidelines about programming SQL based applications in VC++
?
Since MS SQL Server 2008 is strongly promoted, I cannot understand why there
is no help for developers.
There is so many technologies using SQL, but no clear guidelines which one
to use.
Last one I tried is ODBC, but I don't know if I should stick to it.
How to connect and use SQL database from VC++ program in "MS preferred way"
?
Last time when I put such a question to discussion long time ago, everyone
had his own way, and nobody was really happy about it.
Has anything changed in this matter ?

Regards
Pawel
Sep 4 '08 #1
3 2340
"PeeS290" <Pe*****@wp.plwrote in message
news:#d**************@TK2MSFTNGP05.phx.gbl...
Hi all,

Where can I find guidelines about programming SQL based applications in
VC++ ?

Data Access (C++)
http://msdn.microsoft.com/en-us/library/7wtdsdkh.aspx
Mark

--
Mark Salsbery
Microsoft MVP - Visual C++

Sep 4 '08 #2
"PeeS290" <Pe*****@wp.plwrote in message
news:#d**************@TK2MSFTNGP05.phx.gbl...
Hi all,

Where can I find guidelines about programming SQL based applications in
VC++ ?

More managed code info...

Accessing Data (Visual Studio)
http://msdn.microsoft.com/en-us/libr...c4(VS.80).aspx
Mark

--
Mark Salsbery
Microsoft MVP - Visual C++

Since MS SQL Server 2008 is strongly promoted, I cannot understand why
there is no help for developers.
There is so many technologies using SQL, but no clear guidelines which one
to use.
Last one I tried is ODBC, but I don't know if I should stick to it.
How to connect and use SQL database from VC++ program in "MS preferred
way" ?
Last time when I put such a question to discussion long time ago, everyone
had his own way, and nobody was really happy about it.
Has anything changed in this matter ?

Regards
Pawel
Sep 4 '08 #3
PeeS290 wrote:
How to connect and use SQL database from VC++ program in "MS preferred way"
?

I would suggest ADO and COM built-in support. Here is sample program to
get you started. Beware of broken lines.
B.

// This is sample program inserting data to SQL Server database
// using ADO and Visual C++ COM support
//
// The only required parameter is SQL connection string, for example
// "Data Source=.;Integrated Security=SSPI"
//
// I, Bronislaw Kozicki, hereby put this program in public domain
//

#define _CRT_SECURE_NO_WARNINGS
#define STRICT
#define _WIN32_WINNT 0x0500
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>

#include <comdef.h>

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <typeinfo>

#import "C:\Program Files\Common Files\System\ado\msado25.tlb" rename(
"EOF", "ADO_EOF" )

class ctrl
{
static volatile long break_;
static volatile long set_;

static BOOL WINAPI handler_(DWORD)
{
::InterlockedExchange(&break_, 1);
return TRUE; // Leave cleanup to me
}

public:
static void initialize()
{
if (::InterlockedExchange(&set_, 1) == 0)
{
::SetConsoleCtrlHandler(&handler_, TRUE);
}
}

static bool done()
{
return ::InterlockedCompareExchange(&break_, 1, 1) == 1;
}

struct interrupt : std::runtime_error
{
interrupt() : std::runtime_error("User interrupt")
{}
};
};

volatile long ctrl::break_ = 0;
volatile long ctrl::set_ = 0;

class data
{
bool commit_;
ADODB::_ConnectionPtr connection_;
ADODB::_CommandPtr command_;
ADODB::_ParameterPtr fields_[3];

enum Fields {id, name, time};

void execute(const std::string& sql)
{
_variant_t ignore;
connection_->Execute(sql.c_str(), &ignore, ADODB::adExecuteNoRecords
| ADODB::adCmdUnspecified);
}

public:
struct Row {
const int id;
const std::wstring name;
const std::wstring time; // yyyy-mm-dd hh:mi:ss.mmm(24h)
};

data(const std::string& connString)
: commit_(false)
{

_com_util::CheckError(connection_.CreateInstance(_ _uuidof(ADODB::Connection)));

_com_util::CheckError(command_.CreateInstance(__uu idof(ADODB::Command)));

connection_->Provider = L"SQLOLEDB";
connection_->Open(connString.c_str(), L"", L"",
ADODB::adConnectUnspecified);
command_->ActiveConnection = connection_;

execute("USE tempdb");

execute(
"CREATE TABLE #data ("
" [id] int NOT NULL PRIMARY KEY, "
" [name] nvarchar(200) NOT NULL, "
" [time] datetime NULL"
")");

command_->PutPrepared(true);
command_->PutCommandText(
"INSERT INTO #data ([id], [name], [time]) "
" SELECT ?, ?, CONVERT(datetime, ?, 121)" // yyyy-mm-dd
hh:mi:ss.mmm(24h)
);

fields_[id] = command_->CreateParameter(L"id", ADODB::adInteger,
ADODB::adParamInput, 0, _variant_t());
command_->Parameters->Append(fields_[id]);
fields_[name] = command_->CreateParameter(L"name", ADODB::adWChar,
ADODB::adParamInput, 200, _variant_t());
command_->Parameters->Append(fields_[name]);
fields_[time] = command_->CreateParameter(L"time", ADODB::adWChar,
ADODB::adParamInput, 24, _variant_t());
command_->Parameters->Append(fields_[time]);

connection_->BeginTrans();
}

void insert(const Row& r)
{
fields_[id]->PutValue(r.id);
fields_[name]->PutValue(r.name.c_str());
fields_[time]->PutValue(r.time.c_str());

command_->Execute(NULL,NULL,NULL);
}

void commit()
{
connection_->CommitTrans();
connection_->BeginTrans(); // Begin new transaction
}

~data()
{
try
{
connection_->RollbackTrans();
}
catch(_com_error)
{;} // We are in destructor, no exceptions are allowed to leak
}
};

int main(int argc, char* argv[])
{
int result = 13;

try
{
if (::CoInitializeEx(NULL, COINIT_MULTITHREADED |
COINIT_DISABLE_OLE1DDE) != S_OK)
throw std::runtime_error("Failed to initialize COM apartment");

std::vector<std::stringargs(argv, argv + argc);
if (args.size() < 2)
{
throw std::runtime_error(
"Please provide at least complete SQL connection string in
\"quotes\". "
"Optional second argument is number of rows to insert"
);
}

std::cout << "Connecting to \"" << args[1] << "\"" << std::endl;
data d(args[1]);

long rows = 10000;
if (args.size() == 3)
{
long r = 0;
if (sscanf(args[2].c_str(), "%lu", &r) == 1)
rows = r;
}

ctrl::initialize();

std::cout << "Inserting " << rows << " rows of data ..." << std::endl;
for (int i = 0; i < rows; )
{
if (ctrl::done())
{
std::cout << "Committing " << i << " rows" << std::endl;
d.commit();

throw ctrl::interrupt();
}
data::Row r = {i, L"blabla", L"2008-12-31 12:20:21.021"};
d.insert(r);

if (!(++i % 1000))
{
std::cout << i << std::endl;
}
}
std::cout << "Done, committing" << std::endl;
d.commit();

result = 0;
}
catch(ctrl::interrupt& e)
{
std::cerr << e.what() << "\n\n";

result = 0;
}
catch(std::exception& e)
{
std::cerr << typeid(e).name() << " : " << e.what() << "\n\n";

result = 1;
}
catch(_com_error& e)
{
_bstr_t descrB = e.Description(); // Keep the temporary
const char* descr = static_cast<const char*(descrB);
if (!descr)
descr = "(no error description available)";
std::cerr << typeid(e).name() << " : " << descr << "\n\n";

result = 2;
}

::CoUninitialize();

return result;
}

Sep 12 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
by: beliavsky | last post by:
Is there a more recent set of Python style guidelines than PEP 8, "Style Guide for Python Code", by van Rossum and Warsaw, at http://www.python.org/peps/pep-0008.html , which is dated July 5, 2001?
6
by: stevehayter | last post by:
Wonder if anyone can help me solve this problem! I have a 3x3 table which i'm using to create a table with a rounded edge using images in the top left, top right, bottom left, and bottom right...
1
by: Peter Zentner | last post by:
Sorry for that stupid question, but I'm searching for about 4 hours and don't find the stuff. Where are guidelines for creating icons for toolbars etc. that meet the XP guidelines? TIA Peter
61
by: Pete Vidler | last post by:
Hi Folks, I'm wondering if there is a compilation of C++ guidelines out there anywhere. Here are some of the ones I've picked up so far (as examples): - Functions should fit on one screen,...
16
by: E. Robert Tisdale | last post by:
C++ Programming Style Guidelines http://geosoft.no/development/cppstyle.html I think that these guidelines are almost *all* wrong. For example: 11. Private class variables should have...
39
by: jamilur_rahman | last post by:
What is the BIG difference between checking the "if(expression)" in A and B ? I'm used to with style A, "if(0==a)", but my peer reviewer likes style B, how can I defend myself to stay with style A...
5
by: Laurent Bugnion [MVP] | last post by:
Hi group, In agreement with the head of our R&D department, I published my firm's JavaScript Coding Guidelines. I work for Siemens Building Technologies. We developed these guidelines for a web...
5
by: Tony Johansson | last post by:
Hello! Below I have method MostPowerful which is located in class SportsCar. As you can see the fomel parameter for method MostPowerful is carCompare of class SportsCar. Because this method...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.