C ODBC code not working

Following code  connects to database using ODBC calls. I am using VC++
8.0 ( windows server2003 )for compiling this code,and getting lots of
errors. can anybody please help me with this :


#include <windows.h>
#include <sqlext.h>
#include <sql.h>
#include <stdio.h>

main()
{
	SQLHENV     henv;
	SQLHDBC     hdbc;
	SQLHSTMT    hstmt;
	SQLRETURN   retcode;

	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
	retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)
SQL_OV_ODBC3, 0);
       retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
        SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (void*)5, 0);
       retcode = SQLConnect(hdbc, (SQLWCHAR*) "Sales", SQL_NTS,
					  (SQLWCHAR*) "JohnS", SQL_NTS,
					  (SQLWCHAR*) "Sesame", SQL_NTS);
						/* Allocate statement handle*/
       retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);

      if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
				/* Process data */
					  ;
					  ;
					  ;

				   SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
				}
	  SQLDisconnect(hdbc);
	  SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
	  SQLFreeHandle(SQL_HANDLE_ENV, henv);
}


I get these and about 30 such errors :

:\program files\microsoft visual studio
8\vc\platformsdk\include\sqltypes.h(149) : error C2054: expected '(' to
follow 'SQLHWND'
c:\program files\microsoft visual studio
8\vc\platformsdk\include\sqltypes.h(153) : error C2085: 'DATE_STRUCT' :
not in formal parameter list
c:\program files\microsoft visual studio
8\vc\platformsdk\include\sqltypes.h(156) : error C2085: 'DATE_STRUCT' :
not in formal parameter list
c:\program files\microsoft visual studio
8\vc\platformsdk\include\sqltypes.h(156) : error C2146: syntax error :
missing ',' before identifier 'SQL_DATE_STRUCT'


Thanks

0
4/10/2006 10:43:04 AM
vc.mfc 33608 articles. 0 followers. Follow

3 Replies
1228 Views

Similar Articles

[PageSpeed] 53

On 10 Apr 2006 03:43:04 -0700, "priya6122003@rediffmail.com"
<priya6122003@rediffmail.com> wrote:

>Following code  connects to database using ODBC calls. I am using VC++
>8.0 ( windows server2003 )for compiling this code,and getting lots of
>errors. can anybody please help me with this :
>
>
>#include <windows.h>
>#include <sqlext.h>
>#include <sql.h>
>#include <stdio.h>
>
>main()
>{
>	SQLHENV     henv;
>	SQLHDBC     hdbc;
>	SQLHSTMT    hstmt;
>	SQLRETURN   retcode;
>
>	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
>	retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)
>SQL_OV_ODBC3, 0);
>       retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
>        SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (void*)5, 0);
>       retcode = SQLConnect(hdbc, (SQLWCHAR*) "Sales", SQL_NTS,
>					  (SQLWCHAR*) "JohnS", SQL_NTS,
>					  (SQLWCHAR*) "Sesame", SQL_NTS);
>						/* Allocate statement handle*/
>       retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
>
>      if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
>				/* Process data */
>					  ;
>					  ;
>					  ;
>
>				   SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
>				}
>	  SQLDisconnect(hdbc);
>	  SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
>	  SQLFreeHandle(SQL_HANDLE_ENV, henv);
>}
>
>
>I get these and about 30 such errors :
>
>:\program files\microsoft visual studio
>8\vc\platformsdk\include\sqltypes.h(149) : error C2054: expected '(' to
>follow 'SQLHWND'
>c:\program files\microsoft visual studio
>8\vc\platformsdk\include\sqltypes.h(153) : error C2085: 'DATE_STRUCT' :
>not in formal parameter list
>c:\program files\microsoft visual studio
>8\vc\platformsdk\include\sqltypes.h(156) : error C2085: 'DATE_STRUCT' :
>not in formal parameter list
>c:\program files\microsoft visual studio
>8\vc\platformsdk\include\sqltypes.h(156) : error C2146: syntax error :
>missing ',' before identifier 'SQL_DATE_STRUCT'

That's a strange one. When I compile (VC8, WinXP) at the command line, I
get just these errors:

c.cpp(7) : error C4430: missing type specifier - int assumed. Note: C++
does not support default-int
c.cpp(20) : error C2664: 'SQLConnect' : cannot convert parameter 2 from
'SQLWCHAR *' to 'SQLCHAR *'
        Types pointed to are unrelated; conversion requires
reinterpret_cast, C-style cast or function-style cast

The first error has to due with your declaration of main. The second one is
just a character mismatch. I don't get the errors you cited.

I find the following for lines 136-154 in the sqltypes.h file:

*****
#if defined(WIN32) || defined(OS2)
typedef HWND                    SQLHWND;
#elif defined (UNIX)
typedef Widget                  SQLHWND;
#else
/* placehold for future O/S GUI window handle definition */
typedef SQLPOINTER              SQLHWND;
#endif

#ifndef	__SQLDATE
#define	__SQLDATE
/* transfer types for DATE, TIME, TIMESTAMP */
typedef struct tagDATE_STRUCT
{
        SQLSMALLINT    year;
        SQLUSMALLINT   month;
        SQLUSMALLINT   day;
} DATE_STRUCT;
*****

I'd check that your sqltypes.h file looks the same. I'd also try compiling
from the command line as a test. You can compile with /P to create a .i
file that contains the output of the preprocessor, which is what the
compiler sees.


-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
4/10/2006 3:35:50 PM
Thankyou so much for the reply. I reinstalled the studio and now the
code compiles perfectly fine.
but now the SQLConnect function fails,..... i added some error recovery
but the SQLGetDiagRec( ) is returning wierd values.
this is the output i get  :

Failed to connect
The driver reported the following diagnostics whilst running
SQLDriverConnect
:0:0:[  46

Error extraction routine :

void extract_error(
    char *fn,
    SQLHANDLE handle,
    SQLSMALLINT type)
{
    SQLINTEGER	 i = 0;
    SQLINTEGER	 native;
    SQLCHAR	 state[ 7 ] ;
    unsigned char text[1024];
    SQLSMALLINT	 len = 5;
    SQLRETURN	 ret;

    fprintf(stderr,"\n""The driver reported the following diagnostics
whilst running "
            "%s\n\n",fn);
	do
    {
        ret = SQLGetDiagRec(type, handle, ++i, state, &native, &text,
                           sizeof(text), &len );
        if (SQL_SUCCEEDED(ret))
            printf("%s:%ld:%ld:%s  %d\n", state, i, native, text, len);
			//printf("%d\n", state);
    }
    while( ret == SQL_SUCCESS );
}

called in program as :

ret = SQLDriverConnect(dbc, NULL , "DSN=test;", SQL_NTS,
			 0, NULL, 0, SQL_DRIVER_COMPLETE);
  if (SQL_SUCCEEDED(ret)) {
    printf("Connected\n");
    printf("Returned connection string was:\n\t%s\n", outstr);
    if (ret == SQL_SUCCESS_WITH_INFO) {
      printf("Driver reported the following diagnostics\n");
      extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
    }
    SQLDisconnect(dbc);		// disconnect from driver
  } else {
    fprintf(stderr, "Failed to connect\n");
    extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
  }

Actually i dont see any reason why SQLGetDiagRec( ) should fail.
I am fed up with this. could anybody please give me a link to some
working code that connects to SQL server 2000 and has error reporting.
Thanks in advance

0
4/11/2006 10:32:35 AM
On 11 Apr 2006 03:32:35 -0700, "priya6122003@rediffmail.com"
<priya6122003@rediffmail.com> wrote:

>Thankyou so much for the reply. I reinstalled the studio and now the
>code compiles perfectly fine.
>but now the SQLConnect function fails,..... i added some error recovery
>but the SQLGetDiagRec( ) is returning wierd values.
>this is the output i get  :
>
>Failed to connect
>The driver reported the following diagnostics whilst running
>SQLDriverConnect
>:0:0:[  46
>
>Error extraction routine :
>
>void extract_error(
>    char *fn,
>    SQLHANDLE handle,
>    SQLSMALLINT type)
>{
>    SQLINTEGER	 i = 0;
>    SQLINTEGER	 native;
>    SQLCHAR	 state[ 7 ] ;
>    unsigned char text[1024];
>    SQLSMALLINT	 len = 5;
>    SQLRETURN	 ret;
>
>    fprintf(stderr,"\n""The driver reported the following diagnostics
>whilst running "
>            "%s\n\n",fn);
>	do
>    {
>        ret = SQLGetDiagRec(type, handle, ++i, state, &native, &text,
>                           sizeof(text), &len );
>        if (SQL_SUCCEEDED(ret))
>            printf("%s:%ld:%ld:%s  %d\n", state, i, native, text, len);
>			//printf("%d\n", state);
>    }
>    while( ret == SQL_SUCCESS );
>}
>
>called in program as :
>
>ret = SQLDriverConnect(dbc, NULL , "DSN=test;", SQL_NTS,
>			 0, NULL, 0, SQL_DRIVER_COMPLETE);
>  if (SQL_SUCCEEDED(ret)) {
>    printf("Connected\n");
>    printf("Returned connection string was:\n\t%s\n", outstr);
>    if (ret == SQL_SUCCESS_WITH_INFO) {
>      printf("Driver reported the following diagnostics\n");
>      extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
>    }
>    SQLDisconnect(dbc);		// disconnect from driver
>  } else {
>    fprintf(stderr, "Failed to connect\n");
>    extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
>  }
>
>Actually i dont see any reason why SQLGetDiagRec( ) should fail.
>I am fed up with this. could anybody please give me a link to some
>working code that connects to SQL server 2000 and has error reporting.
>Thanks in advance

You might try asking in:

microsoft.public.sqlserver.odbc

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
4/11/2006 1:57:34 PM
Reply:

Similar Artilces:

How to build a project in Visual C++.net developed in Visual C++ 6
Hi, I am Nageshwar. I have developed a project in VC++ 6.0 and OpenGL. I have installed VC++.net in my system. When I compile and build the same code in VC++.net environment, I am getting errors. I have used fstream.h to read and write to files. But this header file is showing errors in VC++.net. I have used iostrea.h header. This is also showing erros. I think I need to use a different version of headers. Please suggest me how to recover from these errors. Which header file I have use instead of fstream.h header? etc., Thanks for all who help me.. Awaiting an early response, Nageshwar ...

VLOOKUP for ZIP codes??
Hi all. I work for a college and we've divided up the country, by zip code, into many many many different regions. What I have is a worksheet in excel that looks like this 'MinZip' 'MaxZip' Region 75000 75899 DALLAS 76000 76899 DALLAS Where MINZIP s the beginning number of a ZIPCode range for a particular region, and MAX is the terminating zip code. On a separate form, I have the listing of our applicants and their zip codes. I was to create a lookup formula that says (in english): If REALZIP is between MINZIP and MAXZIP on row one, re...

Need a program that works with Outlook Express
I know there os a program for downloading that works with Outlook Express. Fixes such things as missing < at the start of reply lines. Can't remember the name nor came I find it searching the Internet. Do you know the name of a program like that. Thanks OE-QuoteFix: http://home.in.tum.de/~jain/software/oe-quotefix/ -- Bruce Hagen MS-MVP [Mail] Imperial Beach, CA " Cal Who" <CalWhoQQ@roadrunner.com> wrote in message news:OTTBNIKbKHA.5796@TK2MSFTNGP06.phx.gbl... >I know there os a program for downloa...

hyperlinks not working
I am currently running Visio Office Standard 2003 (SP2), Internet Explorer 6.0. I have created a test document that I have saved as a web page. I have created a hyperlink to a page within the document. The hyperlink does not work when saved as a web page. I have tried both absolute and relative links. The error is similiar to that described in Article 913756. Any assistance would be appreciated! DeanB ...

Protect Source Code
Dear all, I hire several temporary developers to help me. Can I protect the source code, so they can't take the source code out of office without my permission? Thanks. Vensia Hi, Vensia. > I hire several temporary developers to help me. Can I protect the source > code, so they can't take the source code out of office without my > permission? Of course. All you have to do is all of the following: 1.) Remove their workstations from the network, including any printers, to prevent them from transferring files elsewhere or printing a hard copy that they can take with t...

New Smartlists from SLBuilder only work for me the builder
I have recently installed Smartlist Builder on several user's PC's and have created both new Smartlists & Excel Reports. The Excel Reports that have been deployed work fine for users with access. The Smartlists I have created (along with the downloaded from MS one's) are "visible to the user but no results are returned". So far I have given the users increasing security rights to be able to access the lists. I can log into their machines & run the reports as "sa" and my user id, they don't run under theirs even though they see the l...

C: Drive documents and setting expansion
Whenever I, Right Click Start then click "Explore", I get an expansion of the my user ID folders. Now, I rarely us "Documents and Settings" and would like to have it expand differently. What do I need to change so that can happen?? Thanks.. Bruce A. Julseth wrote: > Whenever I, Right Click Start then click "Explore", I get an > expansion of the my user ID folders. Now, I rarely us "Documents and > Settings" and would like to have it expand differently. > > What do I need to change so that can happen?? 1. You could ...

Currency Code changes?
Have you ever seen it where the currency code changes on its own? Its not a big deal I just changed it back to show a minus sign on credits. But I wonder why it changed to brackets ( ) for a credit currency amount? I went to tools->setup->system -> currency.. Did you change or review your Windows Regional Settings lately. GP takes settings from there for things like date format, etc... -- Lyle U KC wrote: > Have you ever seen it where the currency code changes on its own? > Its not a big deal I just changed it back to show a minus sign on > credits. But I wonder wh...

Would "standard" Billpay plan work with Money?
Recently started using Money 2005. I have already signed up with Online bill payment with my bank and now considering MSN Billpay - mainly to do transfers between various checking accounts. Couple of questions - 1. If I signup with MSN Billpay - would it stop me from using my bank's online bill payment? For any payment would I have the option of choosing my bank's bill payment or MSN Billpay service? 2. If I try to signup for MSN Billpay from billpay.msn.com I get two plans - standard and premium. Whereas if I attempt the signup within Money 2005 I get only Premium option. If ...

New essay and code: Logarithmic Slider
I decided to be positively decadent, so I wrote another essay on a logarthmic slider control http://www.flounder.com/logslider.htm This is missing one feature of the pure-C implementation I give in the Win32 book: it doesn't have logarithmic tick marks. Perhaps someday... joe Joseph M. Newcomer [MVP] email: newcomer@flounder.com Web: http://www.flounder.com MVP Tips: http://www.flounder.com/mvp_tips.htm ...

HELP macro not working
I am attempting to run some macros that transfers an access database to a psql database. I'm not familiar with that particular db technology, but am somewhat familiar with transferring data via ODBC. Anyways when I attempt to run the macro that transfers the data I get ODBC call failed. Unrecognized key passed to SQLGetinfo30. (#209). ...

HELP!! Junk Mail not working
Go to "tools"->"Options" and select the "Preferences" tab. Click on the "Junk mail" button. Select "No automatic filtering" and you are set. Yet 95% of mail goes directly into the Junk Mail folder. Senders in my Safe Sender list go into the Junk Email folder..... What's going on? TIA Harry ...

Writing Code
I am a novice at writing code so I need help. I am trying to create an input box to pop up in an excel form and have the information that was put in the box to drop into a particular cell? Help! sk, You could use something like this: Range("A1").Value = InputBox("Enter your name.") If you want to validate the entry, you can use: Range("A1").Value = Application.InputBox("Enter your name.", , , , , , , 2) which makes Excel validate that the user enters a string. HTH, Bernie MS Excel MVP "sk" <sk@discussions.microsoft.com> wrote in...

Create timeline for 2500 B.C. to 100 B.C.?
Visio only allows me to create timeline for after 1900 AD. Can I use Visio to create a timeline for 2500 BC to 100 BC? Visio's Divided timeline has exactly what I need except I can not enter BC as the start and end time. And Visio always require end time to be greater than the start time. Any suggestion on how I can do this in Visio? You're not going to be able to use the timeline because the code is linked to the system clock (only goes back to 1900). You'll have to use the vanilla shapes that come with visio. Al "Little Black Sheep" <Little Bl...

insert picture from file as a link does not work
I had Publisher 2002 and experienced this problem, so I upgraded to Publisher 2003 hoping that the problem would be fixed, but it is not. I am inserting a picture from a file as a link into a publisher document. I am doing this so I can update the picture periodically and not have to re-do inserting it into the publisher document. This does not work. Whenever I update the file, the linked picture in the document is not updated. Is this a known problem and WHEN will it be fixed? What does 'WHEN' mean in the context you have used it? You can update the original picture, no...

Prevent on Exit code when form is closed
Is there anyway to prevent this code from firing when the form is closed and this text box has focus? Private Sub txtBegHour_Exit(Cancel As Integer) If CInt(Nz(Me.txtBegHour.Text, 0)) = 0 Then MsgBox "Please enter a number between 0 - 12 ", vbOKOnly, "Attention!" Cancel = True End If End Sub Thanks in advance... DJ Move it to the correct event. That would be the Before Update event. -- Dave Hargis, Microsoft Access MVP "DJJ" wrote: > Is there anyway to prevent this code from firing when the form is closed and > this text box has focus? > &g...

Visual C++ to read Strings from Serial Port
Hi. I'm doing a project using Visual C++ to read data from Serial Port. My program needs to do *something* when it receives specific data. For eg, if the program receives "Alarm 1 Zone 4", it will do something. The data received will be variable in length. My questions: 1) Any recommendations for the serial Comm Class for Visual C++? 2) How can i compare the data i receive from serial to the specific messages i'm looking for, eg data types, size of data types, limitations & etc.? Thanks. Any comments are highly appreciated. Leng As far as the serial part goes, it i...

C++ : Is it lots harder than c# and VB
Hi everyone, I learned Java whilst at university and have taught myself c# and VB.net. I think I am ok at it. I was thinking, these languages will probably be bigger in the future so I better get ready for them. But then, I also realised that COM is still quite important and so is C++. So I thought I better just try and have a look at C++ and COM. And now I'm scared. So my question is - why does C++ look so much harder than c#? For example : 1. The methods all have really stupid names that are hard to descern a function from. 2. You need to think about pointers and cleaning up ...

C#.net windows application
Since I am new to c#.net 2008 but I have worked a little with visual basic.net 2005, I have the following questions I would like to ask: 1. When I am looking at a .sln file that I will be maintaining a work, I can see there are lots of static void Main() methods in a file called program.cs throughout the solution in separate folderts. Can you tell me the purpose of this kind of code? Does this instantiate an object, is this a class libary member? 2. When running the C#.net 2008 professional version windows application, how do I know which 'main' method is being called? ...

Changing Start Date affects Duration and/or Work in 2007 (not in 2003)
I've searched all over for this strange behavior but I cannot find anything about it... In my plan there are only Tasks with Type=Fixed Duration and Effort Driven=No. Some Tasks have one of more Resources (type=Work) connected with Calendar=Project Calendar. One of the earliest tasks, planned to be started back in January will probably start now next week (from 22nd Feb), so while updating the plan I have to change that Start Date and after that all FS connected tasks will start at least as many days later as the duration of the changed task. When doing this in Project 2003 t...

MFC DLL Calling C# Assembly
I have been trying to get a simple mfc dll I wrote to add to numbers call a C# assembly. Here is a sample of my C++ code in my cpp file. extern "C" _declspec(dllexport) int Calc(int no1,int no2) { //result = no1 + no2; return MangedAdder(no1, no2); } #pragma managed #using <mscorlib.dll> #using <ControllerLibrary.dll> int MangedAdder(int a, int b) { ControllerLibrary::DLLController *t = new ControllerLibrary::DLLController(); return t->AddNumbers(a, b); } All I really need is an extern function in a mfc dll that calls a me...

BCC not working
I enter the main email address, than continue with the others on the BCC line. Email1; email2; etc. I than click on Hide BCC. After sending, I can go to my sent file, and all the BCC emails show listed in the BCC line. Bob On Fri, 30 Jul 2010 13:19:22 -0400, "The Dog Breeders List" <rltutt@earthlink.net> wrote: >I enter the main email address, than continue with the others on the BCC >line. Email1; email2; etc. I than click on Hide BCC. After sending, I can go >to my sent file, and all the BCC emails show listed in the BCC line. Umm... Yeah, that...

Type Casting in C and C++
Hello NG As an old style programmer I've been casting values with the C-syntax like: double dVal=3.14; float fVal = (float) dVal; but now I've been told that the C++ syntax should do a better job float fVal = static_cast <float>(dVal); for some reason. Is this true? Will the C++ compiler really generate different (better?) code or is it simply more writing I have to do? Thanx Richie >As an old style programmer I've been casting values with the C-syntax like: > >double dVal=3.14; >float fVal = (float) dVal; > >but now I've been told that the C+...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! ...

Money 2007
I recently upgraded from M04 to M07 because it had some bugs that annoyed me, and I wanted to see if any of my FI's had online capability in M07. Well, the online update has been nothing but trouble. I connected directly to Commerce Bank in M04 flawlessly every time, never had a problem. Now in M07, I try all day at different points in the day to get it to connect but it rarely does. I also have an account with a CC company called Direct Merchants Bank. M04 didn't have online access for this, but when I upgraded it was listed. Apparently it doesn't connect directly to the bank th...