473,662 Members | 2,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessing Database from c++

Hai All,

Can anyone suggest or provide me sample code for making ODBC
connection and executing simple queries from c++. I am using sql server
2000. Also please tell what are the header files to be included. I
created a DSN and now I need to make connection with that DSN and
execute query from my code.

Thanks in advance..
Please help!!!! Looking forward for the response.

Jun 16 '06 #1
4 4873
I can provide you a little example ... not in C++ but in C .... you can
modify it and reuse in C++ code.... the only problem is that this
example make an oracle connection... but it should be quite the same...
only the string should change
bye
Pier Paolo

Wallace ha scritto:
Hai All,

Can anyone suggest or provide me sample code for making ODBC
connection and executing simple queries from c++. I am using sql server
2000. Also please tell what are the header files to be included. I
created a DSN and now I need to make connection with that DSN and
execute query from my code.

Thanks in advance..
Please help!!!! Looking forward for the response.

#include <stdio.h>
#include "sqlmine.h"
struct data {
char nome[1024];
int nomelen;
SQL_TIMESTAMP_S TRUCT ora;
int oralen;
} data1;

void usa(void *altro)
{
printf("nome %s data creazione ",data1.nom e);
if (data1.oralen!= 0)
printf("%d-%d-%d:%d:%d:%d\n", data1.ora.year, data1.ora.month ,data1.ora.day, data1.ora.hour, data1.ora.minut e,data1.ora.sec ond);
}

SQLRETURN sqltrybind(SQLH ANDLE *sqlstmt)
{
int res;
res= SQLBindCol(sqls tmt,
1,
SQL_C_CHAR,
&(data1.nome ),
1024,
&data1.nomelen) ;

res=res+SQLBind Col(sqlstmt,
2,
SQL_C_TYPE_TIME STAMP,
&(data1.ora) ,
1024,
&data1.orale n);
return res;
}

int sqlconnect(char *server,char *user,char *pwd)
{
int res;
if (res=SQLAllocHa ndle(SQL_HANDLE _ENV,SQL_NULL_H ANDLE,&sqlenv)! =SQL_SUCCESS) printf("Errore in allocEnv\n");
if (res=res*SQLSet EnvAttr( sqlenv,SQL_ATTR _ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER )!=SQL_SUCCESS) printf("Errore in SQLATTREnv\n");
if (res=res*SQLAll ocHandle(SQL_HA NDLE_DBC,sqlenv ,&sqlconn) != SQL_SUCCESS)
{
printf("Errore in allocConn %d\n",res);
}
if (res=res*SQLCon nect(sqlconn,se rver,strlen(ser ver),user,strle n(user),pwd,str len(pwd))!=SQL_ SUCCESS) printf("Errore in Connessione\n") ;
return res;
}

/* Esegue Select */
void sqlselect(char *select, sqlbind sqlb,void *altro,usedata used)
{
int res;
SQLHANDLE sqlstmt;
res=SQLAllocHan dle(SQL_HANDLE_ STMT,sqlconn,&s qlstmt);
if (res==SQL_SUCCE SS) printf("Errore in creazione Handle Statement\n");
res=SQLPrepare( sqlstmt,select, strlen(select)) ;
if (res==SQL_SUCCE SS) printf("Errore in creazione SQLPrepare\n");
sqlb(sqlstmt);
SQLExecute(sqls tmt);
while (SQLFetch(sqlst mt)==SQL_SUCCES S)
{
used(altro);
}
SQLFreeHandle(S QL_HANDLE_STMT, sqlstmt);
}

void esegui()
{
sqlconnect("TES T","SYSTEM","MA NAGER");
sqlselect("sele ct object_name,cre ated from user_objects",s qltrybind,NULL, usa);
sqlDisconnect() ;
}

/* Disconnect */
void sqlDisconnect()
{
SQLDisconnect(s qlconn);
SQLFreeHandle(S QL_HANDLE_DBC,s qlconn);
SQLFreeHandle(S QL_HANDLE_DBC,s qlenv);
}
#include <sql.h>
#include <sqlext.h>

typedef SQLRETURN (*sqlbind)(SQLH ANDLE *sqlstmt);
typedef void (*usedata)(void *altro);
SQLHANDLE sqlenv;
SQLHANDLE sqlconn;

int sqlconnect(char *server,char *user,char *pwd);
void sqlDisconnect() ;
void sqlselect(char *select, sqlbind sqlb,void *altro,usedata used);

#include <windows.h>
#include <string.h>
#include <io.h>
#include <stdio.h>
#include <fcntl.h>
#include <commctrl.h>
HINSTANCE hinstp;
void startDebug();
int leggi(HWND hwnd,int obj,char *buffer,int size);
char username[256];
char datasource[256];
char pwd[256];

#include "common.h"

void startDebug()
{
int hCrt,hCrti,hCrt e;
FILE *hf,*hfi,*hfe;
AllocConsole();
hCrt = _open_osfhandle ((long)GetStdHa ndle ( STD_OUTPUT_HAND LE),_O_TEXT );
hf = fdopen( hCrt, "w" );
*stdout = *hf;
setvbuf( stdout, NULL, _IONBF, 0 );

hCrti = _open_osfhandle ((long) GetStdHandle ( STD_INPUT_HANDL E),_O_TEXT );
hfi = fdopen( hCrti, "r" );
*stdin = *hfi;
setvbuf( stdin, NULL, _IONBF, 0 );

hCrte = _open_osfhandle ((long)GetStdHa ndle ( STD_OUTPUT_HAND LE),_O_TEXT );
hfe = fdopen( hCrte, "w" );
*stderr = *hfe;
setvbuf( stderr, NULL, _IONBF, 0 );

}
int leggi(HWND hwnd,int obj,char *buffer,int size)
{
memset(buffer,0 ,size);
if (GetDlgItemText (hwnd, obj, buffer, size)) {
printf("%s\n",b uffer);
return 1;
}
return 0;
}
Jun 16 '06 #2

Wallace wrote:
Can anyone suggest or provide me sample code for making ODBC
connection and executing simple queries from c++. I am using sql server
2000. Also please tell what are the header files to be included. I
created a DSN and now I need to make connection with that DSN and
execute query from my code.


If you're using MSVC and you are willing to use ADO then it's really
simple. Just use:

#import <c:\program files\common files\system\ad o\msado15.dll> rename(
"EOF", "adoEOF" )

Something like this will open a connection:

ADODB::_Connect ionPtr writeCnx;
writeCnx = ADODB::_Connect ionPtr();
writeCnx.Create Instance( __uuidof( ADODB::Connecti on ) );
writeCnx->CommandTimeo ut = 60;
writeCnx->Open( writeDsn().c_st r(), L"", L"",
ADODB::adConnec tUnspecified );

To execute SQL then use something like this:

ADODB::_Records etPtr rs;
rs = writeCnx->Execute( cmd.c_str(), &res, ADODB::adOption Unspecified
);

I'll leave it as an excercise to get the data out. Read the ADO COM
spec to work it out. It's actually all pretty easy.
K

Jun 16 '06 #3
[ODBC Request and sample code reply redacted]

1. Please do not post attachments to comp.lang.c++. See the FAQ
http://www.parashift.com/c++-faq-lit...t.html#faq-5.4

2. This is Off Topic. See the FAQ
http://www.parashift.com/c++-faq-lit...t.html#faq-5.9

A newsgroup with "microsoft" , "windows", or "database" in the name would
be more appropriate.
Jun 16 '06 #4

"Wallace" <pr************ ****@gmail.com> wrote in message
news:11******** **************@ g10g2000cwb.goo glegroups.com.. .
Hai All,

Can anyone suggest or provide me sample code for making ODBC
connection and executing simple queries from c++. I am using sql server
2000. Also please tell what are the header files to be included. I
created a DSN and now I need to make connection with that DSN and
execute query from my code.

Thanks in advance..
Please help!!!! Looking forward for the response.


If you are using Windows, I suggest you look at:
http://msdn.microsoft.com/data/learning/MDAC/
Jun 17 '06 #5

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

Similar topics

3
2727
by: Scott Castillo | last post by:
Is it possible to access an SQL Server database from a Javascript client? I know you can transfer variables from middleware to Javascript client, but was wondering if you can directly access database from client? Thanks for any response. Scott
2
7074
by: Douglas Harber | last post by:
If I have DB2 8.1 (FP5, I believe, but not relevant to my question...I hope) installed on my desktop, do I have what I need to connect to a remote DB2 server (also running 8.1 FP5) from my desktop machine? I assume, perhaps naively, that all the parts are there but I've spent several hours trying to grasp how to go about accessing the remote server. Specifically, I'm trying to create and populate databases on the remote server from...
3
4313
by: prodirect | last post by:
Hi all, I hope someone can help me. I've recently created a database and wanted to put it up on an ftp sight so that multiple people could access the same tables at the same time from different geographical locations. I have been completely unsucessful in acheiving this goal so far however. Things I have tried: Create a shortcut to ftp sight via browser then tried to map local drive to
2
1809
by: DanB | last post by:
I am using VB DotNet Std Edition and am writing a web application that needs to read and write to an password protected database. The mdb files reside in a folder (fpdb) under the localhost (c:\inetpub\wwroot) Within the IDE I can view the data using the server explorer and I use that same oledb connection for the web form. I have tried accessing a non-password protected db in the same folder using
3
1921
by: mark.jerrom | last post by:
I'm fairly new to this Web Service game so please feel free to suggest something different if it looks like i'm completely off track! I'm trying to write an application that runs on a Pocket PC that is accessing data stored in a SQL server database on a seperate server (not on the pocket pc). This wil be deployed to lots of customers sites so I can't hard-code the location of the database in the program. I wrote a seperate little app...
3
2684
by: Pakna | last post by:
Hello, I have what may be a beginner's question regarding DB2. How does one access a remote table on a remote database via SQL? What is the command string, is there an equivalent of Oracle DBLINK? I hope I was clear. If there are more information that I need to supply, please do tell me. Thank you very much for your replies
5
2256
by: samadams_2006 | last post by:
I'm having a problem in accessing a Microsoft Access Database in a VB.NET Web Application. It's so straight forward, I thought I'd walk you through all the details here: 1) I have a .NET Web Application called "Lesson18b" under "C:\Inetpub\wwwroot\Lesson18b". 2) I have one Web Form on this Lesson called "Form18b.aspx" 3) In this same Folder under Inetpub I have the Microsoft NorthWinds
4
2757
by: scout3014 | last post by:
Hi I am using WAMP5 to create web applications. I have a problem as far as accessing the database is concerned. This following code is used to access database: $con = mysql_connect("localhost", "root", ""); if (!con) { die('Could not Connect' . mysql_error()); }
4
4218
by: Noy B | last post by:
Hi, I have developed a small application that is using a MSAccess DB. the problem is that it was developed on a machine where the application and the DB are both located. now it needs to be change that the application will be able to run on any other machine (using \\ syntax on the run command- not a problem) using the DB located on a static-different machine. for this purpose I need to create a Remote Connection from my
2
1745
by: brendan_gallagher_2001 | last post by:
HI I am developog an ASP.net site (using vb.net 1.1) which will be accessed by a number of different office locations, where certain users will be assigned a authoriser profile, and others will be assigned a verifier profile. At least two authoriser, and multiple verifiers exist per office. I need to be able to prevent two users with the same profile, and from the same office location, accessing the same page at the same time. I
0
8435
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8547
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7368
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4181
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.