Connexion ODBC avec SQLConnect

gagaet22 Messages postés 32 Date d'inscription vendredi 7 février 2003 Statut Membre Dernière intervention 17 janvier 2005 - 5 janv. 2004 à 20:48
cs_unique07 Messages postés 8 Date d'inscription vendredi 2 mai 2008 Statut Membre Dernière intervention 29 juillet 2010 - 12 juil. 2010 à 09:25
Bonjour à tous et bonne année!!!! Et la santé aussi (quand la santé va tout va !!!)

Voila, je suis en train de decouvrir ODBC avec mes petits moyens. Mais voila, je n arrive pas à effectuer une connexion... j'ai cherché ( un bon paquet de tps, d ailleurs
:( ) et je trouve pas alors si quelqu un peut regarder le code.... ca m aiderais!!! Je cale et ca m enerve !!! (un peu)

retcode=SQLConnect(hdbc, (SQLCHAR*)Serveur, SQL_NTS, (SQLCHAR*)Login, SQL_NTS, (SQLCHAR*)Pwd, SQL_NTS);

//code complet

#include <windows.h>

#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Les defines

#define EXPORT_FILE "./test.txt"

// Les types SQL
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;

int main()
{
// Déclaration des variables SQL
SQLRETURN retcode;
SQLINTEGER cbville, cbnom, cbprenom;
SQLCHAR szville[81],sznom[81],szprenom[81];

// Déclaration des variables Standart
char requete[1024+1]="select ville,nom,prenom from Liste ";
char Serveur[81]="Provider=MSDASQL.1;Persist Security Info=False;Data Source=MS Access Database";
char Login[81]="";
char Pwd[81]="";
FILE *fp;

// Connexion à la base de données
retcode=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if(retcode SQL_SUCCESS || retcode SQL_SUCCESS_WITH_INFO)
retcode=SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3,0);
if(retcode SQL_SUCCESS || retcode SQL_SUCCESS_WITH_INFO)
retcode=SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
else
printf("Erreur sur l'instruction SQLAllocHandle !\\n");

// Vérification du Lien ODBC, Login Et Pwdif(retcode SQL_SUCCESS || retcode SQL_SUCCESS_WITH_INFO)
retcode=SQLConnect(hdbc, (SQLCHAR*)Serveur, SQL_NTS, (SQLCHAR*)Login, SQL_NTS, (SQLCHAR*)Pwd, SQL_NTS);
else
printf("Erreur sur l'instruction SQLSetEnvAttr !\\n");if(retcode SQL_SUCCESS || retcode SQL_SUCCESS_WITH_INFO)
retcode=SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
else
printf("Erreur sur l'instruction SQLConnect !\\n");

// Execution de la requeteif(retcode SQL_SUCCESS || retcode SQL_SUCCESS_WITH_INFO)
retcode=SQLExecDirect(hstmt, (SQLCHAR*)requete, SQL_NTS);
else
printf("Erreur sur l'instruction SQLAllocHandle !\\n");
if (retcode SQL_SUCCESS || retcode SQL_SUCCESS_WITH_INFO)
{
// Récupération des informations contenu dans les champs des tables
SQLBindCol(hstmt, 1, SQL_C_CHAR, szville,80, &cbville);
SQLBindCol(hstmt, 2, SQL_C_CHAR, sznom, 80, &cbnom);
SQLBindCol(hstmt, 3, SQL_C_CHAR, szprenom, 80, &cbprenom);

}
else
printf("Erreur sur l'instruction SQLExecDirect !\\n");

// Déconnexion
SQLFreeStmt(hstmt, SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeConnect(hdbc);

return 0;
}

4 réponses

BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019
5 janv. 2004 à 20:56
Pas le temps de verifier alors je te mets un exemple perso qui va bon.

#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include "McrAsm.h"

#pragma comment(lib, "odbc32.lib")

HINSTANCE hinst;
SQLHANDLE henv, hconn;
long lerror = 0;

char szbuff[1024];
char *szappname = "Connect";

int OdbcConnEnvCreate()
{
SQLRETURN retcd;
retcd = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if(retcd == SQL_SUCCESS) goto envOK;
if(retcd == SQL_SUCCESS_WITH_INFO) goto envOK;
strcpy(szbuff, "Environment handle allocation failed");
goto errMsg;
envOK:
retcd = SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3,0);
if(retcd == SQL_SUCCESS) goto versOK;
if(retcd == SQL_SUCCESS_WITH_INFO) goto versOK;
strcpy(szbuff, "ODBC version incorrecte");
goto envOut;
versOK:
retcd = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hconn); if((retcd SQL_SUCCESS) || (retcd SQL_SUCCESS_WITH_INFO)) return 1;
strcpy(szbuff, "Connection handle allocation failed");
envOut:
SQLFreeHandle(SQL_HANDLE_ENV, henv);
errMsg:
MessageBox(0, szbuff, szappname, MB_ICONERROR);
return 0;
}

int OdbcMdbConnect(int unic, int rdonly, char* dbname, char* dbpwd) // les 2 char* options
{
SQLRETURN retcd;
retcd = SQLSetConnectAttr(hconn, SQL_ATTR_ACCESS_MODE, (SQLPOINTER)SQL_MODE_READ_ONLY, 0);
char *c = bnstrcpy(szbuff, "DRIVER={Microsoft Access Driver (*.mdb)};");
if(unic) c = bnstrcpy(c, "EXCLUSIVE=1;"); *c 'D'; *(c+1) 'B'; *(c+2) = 'Q'; *(c+3) = '='; *(c+4) = 0;
if(rdonly) SQLSetConnectAttr(hconn, SQL_ATTR_ACCESS_MODE, (SQLPOINTER)SQL_MODE_READ_ONLY, 0);
if(dbname) {
c += 4;
if(dbname[0]) {
c = bnstrcpy(c, dbname);
if(dbpwd) {
if(dbpwd[0]) { *c ';'; *(c+1) 'P'; *(c+2) = 'W'; *(c+3) = 'D'; *(c+4) = '=';
c = bnstrcpy(c+5, dbpwd);
}
}
}
}
retcd = SQLDriverConnect(hconn, 0, (SQLCHAR*)szbuff, c - szbuff,
0, 0, 0, SQL_DRIVER_COMPLETE_REQUIRED); if((retcd SQL_SUCCESS) || (retcd SQL_SUCCESS_WITH_INFO)) return 1;
SQLFreeHandle(SQL_HANDLE_DBC, hconn);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}

void AppPathInitialize()
{
char szThis[300];
char* c = szThis + GetModuleFileName(NULL, szThis, 300); while(*c !'\\\\') c--; *c 0;
SetCurrentDirectory(szThis);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, int)
{
hinst = hInstance;
AppPathInitialize();

if(!OdbcConnEnvCreate()) return 0;

if(!OdbcMdbConnect(1 , 0, "Mybase.mdb", 0)) return 0;

MessageBox(0, "OK", szappname, MB_ICONINFORMATION);
SQLDisconnect(hconn);
SQLFreeHandle(SQL_HANDLE_DBC, hconn);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}

BruNews, ciao...
0
gagaet22 Messages postés 32 Date d'inscription vendredi 7 février 2003 Statut Membre Dernière intervention 17 janvier 2005
5 janv. 2004 à 21:17
Je te remercie, mais je souhaite utiliser SQLConnect afin d'automatiser la connexion à la base de donnée. Je pourrais aussi utiliser Open ??? Mais j aime pas bloquer devant une fonction....
0
BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019
5 janv. 2004 à 21:38
Alors tire direct de MSDN:

#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <stdlib.h>
#include <mbstring.h>

#define MAX_DATA 100
#define MYSQLSUCCESS(rc) ((rc==SQL_SUCCESS)||(rc==SQL_SUCCESS_WITH_INFO))

class direxec
{
RETCODE rc; // ODBC return code
HENV henv; // Environment
HDBC hdbc; // Connection handle
HSTMT hstmt; // Statement handle
unsigned char szData[MAX_DATA]; // Returned data storage
SDWORD cbData; // Output length of data
unsigned char chr_ds_name[SQL_MAX_DSN_LENGTH]; // Data source name

public:
direxec(); // Constructor
void sqlconn(); // Allocate env, stat, and conn
void sqlexec(unsigned char *); // Execute SQL statement
void sqldisconn(); // Free pointers to env, stat, conn,
// and disconnect
void error_out(); // Displays errors
};

// Constructor initializes the string chr_ds_name with the
// data source name.
direxec::direxec()
{
_mbscpy(chr_ds_name,(const unsigned char *)"Northwind");
}

// Allocate environment handle, allocate connection handle,
// connect to data source, and allocate statement handle.
void direxec::sqlconn(void)
{
SQLAllocEnv(&henv);
SQLAllocConnect(henv,&hdbc);
rc=SQLConnect(hdbc,chr_ds_name,SQL_NTS,NULL,0,NULL,0);

// Deallocate handles, display error message, and exit.
if (!MYSQLSUCCESS(rc))
{
SQLFreeEnv(henv);
SQLFreeConnect(hdbc);
error_out();
exit(-1);
}

rc=SQLAllocStmt(hdbc,&hstmt);

}

// Execute SQL command with SQLExecDirect() ODBC API.
void direxec::sqlexec(unsigned char * cmdstr)
{
rc=SQLExecDirect(hstmt,cmdstr,SQL_NTS);
if (!MYSQLSUCCESS(rc)) //Error
{
error_out();
// Deallocate handles and disconnect.
SQLFreeStmt(hstmt,SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeConnect(hdbc);
SQLFreeEnv(henv);
exit(-1);
}
else
{
for (rc=SQLFetch(hstmt); rc == SQL_SUCCESS; rc=SQLFetch(hstmt))
{
SQLGetData(hstmt,1,SQL_C_CHAR,szData,sizeof(szData),&cbData);
// In this example, the data is returned in a messagebox
// for simplicity. However, normally the SQLBindCol() ODBC API
// could be called to bind individual rows of data and assign
// for a rowset.
MessageBox(NULL,(const char *)szData,"ODBC",MB_OK);
}
}
}

// Free the statement handle, disconnect, free the connection handle, and
// free the environment handle.
void direxec::sqldisconn(void)
{
SQLFreeStmt(hstmt,SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeConnect(hdbc);
SQLFreeEnv(henv);
}

// Display error message in a message box that has an OK button.
void direxec::error_out(void)
{
unsigned char szSQLSTATE[10];
SDWORD nErr;
unsigned char msg[SQL_MAX_MESSAGE_LENGTH+1];
SWORD cbmsg;

while(SQLError(0,0,hstmt,szSQLSTATE,&nErr,msg,sizeof(msg),&cbmsg)==
SQL_SUCCESS)
{
wsprintf((char *)szData,"Error:\\nSQLSTATE=%s,Native
error=%ld,msg='%s'",
szSQLSTATE,nErr,msg);
MessageBox(NULL,(const char *)szData,"ODBC Error",MB_OK);

}

}

int WINAPI WinMain (HANDLE hInstance, HANDLE hPrevInstance,
LPSTR lpszCmdLine, int nCmdShow)
{
// Declare an instance of the direxec object.
direxec x;

// Allocate handles, and connect.
x.sqlconn();

// Execute SQL command "SELECT first name, last_name FROM employee".
x.sqlexec((UCHAR FAR *)"SELECT first name, last_name FROM employee");

// Free handles, and disconnect.
x.sqldisconn();

// Return success code; example executed successfully.
return (TRUE);
}

BruNews, ciao...
0
cs_unique07 Messages postés 8 Date d'inscription vendredi 2 mai 2008 Statut Membre Dernière intervention 29 juillet 2010
12 juil. 2010 à 09:25
salut tout le monde!!
je voulais établir une connexion ODBC avec mySql, la connexion est bien établie...mon souci est la requête SQL... j'ai une seule erreur
ERROR C2664:'SQLExecDirect': impossible de convertir le paramètre 2 de 'const char [19] en 'SQLCHAR *
si qlq'un a une idée sur ce problème je serais très reconnaissant
Merci d'avance!
voici mon code
#include <conio.h>
#include <stdio.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>

int main()
{
SQLHENV env;

IF( !SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, NULL, &env)))
fprintf(stderr, "La fonction SQLAllocHandle a echoue
(SQL_HANDLE_ENV).\n");
else
{
IF( !SQL_SUCCEEDED(SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION,
(void *)SQL_OV_ODBC3, 0)))
fprintf(stderr, "La fonction SQLSetEnvAttr a echoue.\n");
else
{
SQLHDBC con;

IF( !SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC, env,
&con)))
fprintf(stderr, "La fonction SQLAllocHandle a echoue
(SQL_HANDLE_DBC).\n");
else
{
SQLCHAR dsn[] = "pays_dsn", uid[] = "root", pwd[] =
"";

IF( !SQL_SUCCEEDED(SQLConnect(con, dsn, SQL_NTS, uid,
SQL_NTS, pwd, SQL_NTS)))
// IF( !SQL_SUCCEEDED(SQLConnect(con,(SQLCHAR *)"pays_dsn",
SQL_NTS,(SQLCHAR *)"root", SQL_NTS,(SQLCHAR *)"", SQL_NTS)))
fprintf(stderr, "La fonction SQLConnect a echoue.
\n");
else
{
SQLHSTMT stmt;

IF( !SQL_SUCCEEDED(SQLAllocHandle
(SQL_HANDLE_STMT, con, &stmt)))
fprintf(stderr, "La fonction SQLAllocHandle a
echoue (SQL_HANDLE_STMT).\n");
else
{
IF( !SQL_SUCCEEDED(SQLExecDirect(stmt,
"SELECT * FROM pays_tbl;", SQL_NTS)))
fprintf(stderr, "La fonction SQLExecDirect
a echoue.\n");
else
{
SQLCHAR pays[15], capitale[15];

printf("PAYS > CAPITALE\n\n");

while (SQL_SUCCEEDED(SQLFetch(stmt)))
{
SQLGetData(stmt, 1, SQL_C_CHAR, pays,
sizeof(pays), NULL);
SQLGetData(stmt, 2, SQL_C_CHAR,
capitale, sizeof(capitale), NULL);
printf("%-14s %-14s\n", pays,
capitale);
}
}

SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}

SQLDisconnect(con);
}

SQLFreeHandle(SQL_HANDLE_DBC, con);
}
}

SQLFreeHandle(SQL_HANDLE_ENV, env);
}
getch();
RETURN0;

}
0
Rejoignez-nous