Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • Last Modified:

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

How do I connect to MS SQL Server thru C or C++ ?
Any samples ?
0
qetuo08
Asked:
qetuo08
1 Solution
 
makerpCommented:
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
 
qetuo08Author Commented:
is there any URL tutorial for this ?
0
 
qetuo08Author Commented:
How to use DSN less connection ?
0
The Firewall Audit Checklist

Preparing for a firewall audit today is almost impossible.
AlgoSec, together with some of the largest global organizations and auditors, has created a checklist to follow when preparing for your firewall audit. Simplify risk mitigation while staying compliant all of the time!

 
qetuo08Author Commented:
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
 
makerpCommented:
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
 
makerpCommented:
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
 
qetuo08Author Commented:
makerp,

Where can I get tutorials for this ?
0
 
makerpCommented:
look on MSDN for examples, VC++ has some info in the help section.

are you going to close this question
0
 
MoondancerCommented:
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
 
NetminderCommented:
Question abandoned; force-accepted.

Netminder
CS Moderator
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now