Solved

How do I connect to MS SQL thru C/C++ ?

Posted on 2001-06-21
11
350 Views
Last Modified: 2012-08-14
How do I connect to MS SQL Server thru C or C++ ?
Any samples ?
0
Comment
Question by:qetuo08
11 Comments
 
LVL 10

Accepted Solution

by:
makerp earned 70 total points
ID: 6217515
this is a simple example ive knocked up, create a simple oracle/sql server/access database and create
a system dsn for it in control panel. the open function uses global varaibles etc so you will probably want to chage this.

it uses ODBC and was written in VC++

/* for db stuff */
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <stdio.h>

HENV henv;
HDBC hdbc;
int dbopen=0;

/* opens a connection using global variables , bad i know */
#define PM_DSN "your_system_dsn"
#define PM_DSN_USER "your_db_username_if_any"
#define PM_DSN_PW "your_password_if_any"

int DBopen(void)
{
   int res=0;
   RETCODE retcode;
   /*allocate the environment handle*/
   if(SQLAllocEnv(&henv)==SQL_SUCCESS)
   {
        /*allocate the connection handle*/
        if(SQLAllocConnect(henv, &hdbc)==SQL_SUCCESS)
        {
             /* Set login timeout to 5 seconds. */
             SQLSetConnectOption(hdbc, SQL_LOGIN_TIMEOUT, 5);
             SQLSetConnectOption(hdbc, SQL_CURSOR_TYPE, SQL_CURSOR_STATIC);
             /* Connect to data source */
             retcode = SQLConnect(hdbc, PM_DSN, SQL_NTS, PM_DSN_USER, SQL_NTS, PM_DSN_PW, SQL_NTS);


             if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
             {
                       res=1;
                       DATABASE_NAME = getDBName();
             }
        }
        else
        {
             SQLFreeConnect(hdbc);
        }
   }
   else
   {
        SQLFreeEnv(henv);
   }
   dbopen=res;
   return res;
}

void DBclose(void)
{
   if(dbopen)
   {
        SQLDisconnect(hdbc);
        SQLFreeConnect(hdbc);
        SQLFreeEnv(henv);
        if(DATABASE_NAME)
        {
             free(DATABASE_NAME);
        }
   }
   dbopen=0;
}
int DBexecute(char *sql,HSTMT *hstmt)
{
   int res=0;
   RETCODE retcode;

   if(SQLAllocStmt(hdbc, hstmt)== SQL_SUCCESS)
   {
        retcode=SQLPrepare(*hstmt,sql,strlen(sql) + 1);
        if(retcode==SQL_SUCCESS)
        {
             retcode=SQLExecute(*hstmt);
             if(retcode==SQL_SUCCESS)
             {
                  res=1;
             }
        }
   }
   return res;
}

void DBcloseCursor(HSTMT hstmt)
{
   SQLFreeStmt(hstmt, SQL_DROP);
}

void main()
{
   char sql[255];
   HSTMT fstmt;
   long lens;
   RETCODE retcode;
   char name[100];

   DBopen();

   sprintf(sql,"SELECT name FROM users");
   if(DBexecute(sql,&fstmt))
   {      
        SQLBindCol(fstmt,1,SQL_C_CHAR, name,sizeof(name),&lens);
       
        retcode = SQLFetch(fstmt);    
        while(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
        {
             printf("%s\n",name);
             retcode = SQLFetch(fstmt);
        }
        DBcloseCursor(fstmt);
   }
   else
   {  
        printf("DBexecute failure : %s\n",getStmtError(fstmt));    
        exit(1);
   }
   DBclose();
}
0
 

Author Comment

by:qetuo08
ID: 6221838
is there any URL tutorial for this ?
0
 

Author Comment

by:qetuo08
ID: 6221851
How to use DSN less connection ?
0
 

Author Comment

by:qetuo08
ID: 6221872
When I compiled, I got these errors :
D:\VC\test\test.c(28) : warning C4013: 'getDBName' undefined; assuming extern returning int
D:\VC\test\test.c(28) : warning C4047: '=' : 'char *' differs in levels of indirection from 'int '
D:\VC\test\test.c(89) : warning C4013: 'getStmtError' undefined; assuming extern returning int

test.obj - 0 error(s), 3 warning(s)

When I built the exe, I got this errors:

test.obj : error LNK2001: unresolved external symbol _getDBName
test.obj : error LNK2001: unresolved external symbol _getStmtError
Debug/test.exe : fatal error LNK1120: 2 unresolved externals
Error executing link.exe.

0
 
LVL 10

Expert Comment

by:makerp
ID: 6222526
printf("DBexecute failure : %s\n",getStmtError(fstmt));    

lose that line, i can not find that function in my files, it gets error expaination after an error, and

DATABASE_NAME = getDBName();

lose that too, it in open

nither changes will effect the code
 
0
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 
LVL 10

Expert Comment

by:makerp
ID: 6222527
i dont know how to do DSN-Less connections, for that you may need to use CDAODatabase or CDatabase, these are MFC and miles away from C
0
 

Author Comment

by:qetuo08
ID: 6222915
makerp,

Where can I get tutorials for this ?
0
 
LVL 14

Expert Comment

by:AlexVirochovsky
ID: 6247618
0
 
LVL 10

Expert Comment

by:makerp
ID: 6332210
look on MSDN for examples, VC++ has some info in the help section.

are you going to close this question
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 7024680
Greetings.  You've asked 7 questions, which need your attention.  ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101, Netminder, Mindphaser or I will return to finalize these as soon as possible if after 7 days no response by the Asker.  EXPERTS-->  please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.20139268.html
http://www.experts-exchange.com/questions/Q.20170838.html
http://www.experts-exchange.com/questions/Q.20171602.html
http://www.experts-exchange.com/questions/Q.20181175.html
http://www.experts-exchange.com/questions/Q.20191372.html
http://www.experts-exchange.com/questions/Q.20226904.html
http://www.experts-exchange.com/questions/Q.20241247.html



*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643 
------> POINTS FOR EXPERTS awaiting comments are listed in the links below
http://www.experts-exchange.com/commspt/Q.20277028.html (Part 1)
http://www.experts-exchange.com/jsp/qShow.jsp?ta=commspt&qid=20295853 (Part 2)
 
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thanks everyone.
Moondancer
Moderator @ Experts Exchange
0
 
LVL 5

Expert Comment

by:Netminder
ID: 7329686
Question abandoned; force-accepted.

Netminder
CS Moderator
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Which checksum is this? 7 139
Which version of C should I use when Perl is too slow? 13 173
C simple state machine for client server handshake 4 268
Problem to show menu 5 87
Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

896 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now