First step: Configure ODBC. There are three ways to configure ODBC with a User DSN, System DSN, and File DSN, and for the sake of security, a System DSN is used.
DSN is named LocalServer, account number: SA, password 123456
The second step: Open VC, Build a Win32 Console Application project, the name can be casually;
The third step: Create a new file, the file name can be arbitrarily;
Fourth step: Copy the following code:
#include <stdio.h>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <odbcss.h>
int main ()
{
void SqlConnect ();
SqlConnect ();
GetChar ();
return 0;
}
void SqlConnect ()
{
Sqlhenv henv;
SQLHDBC HDBC;
SQLHSTMT hstmt;
Sqlreturn Retcode;
UCHAR sql1[79]= "Select No from Student wherename= ' Jim '";
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);
if (retcode==sql_success| | retcode==sql_success_with_info)
{
Retcode=sqlconnect (HDBC, (sqlchar*) "LocalServer", Sql_nts, (sqlchar*) "sa", Sql_nts, (sqlchar*) "123456", SQL_NTS);
if (retcode==sql_success| | retcode==sql_success_with_info)
{
Retcode=sqlallochandle (SQL_HANDLE_STMT,HDBC,&HSTMT);
if (retcode==sql_success| | retcode==sql_success)
{
Binding parameter Mode
Chara[20]= "Jim";
sqlintegerp=sql_nts;
1. Pre-compilation
SQLPrepare (hstmt,sql1,79);//The third parameter is the same as the array size, not the same as the database column
2. Binding parameter values
SQLBindParameter (HSTMT,1,SQL_PARAM_INPUT,SQL_C_CHAR,SQL_CHAR,200,0,&A,0,&P);
SQLExecute (HSTMT);
printf ("Connectionis ok\n");
SQLExecDirect (hstmt,sql1,79);
CHARLIST[5];
SQLBindCol (hstmt,1,sql_c_char,list,5,0);
SQLFetch (HSTMT);
printf ("%s\n", list);
}
SQLDisconnect (HDBC);
}
Sqlfreehandle (SQL_HANDLE_DBC,HDBC);
}
}
}
}
C language connection to SQL Server database