Click here to Skip to main content
Licence 
First Posted 13 May 2002
Views 115,980
Bookmarked 30 times

Connecting to SQL Server

By | 13 May 2002 | Article
This article explains how to connect to an SQL Server and pass a string.
 
Part of The SQL Zone sponsored by
See Also

Introduction

This article explains how to get connected to SQL Server database and then write string in the database table using an SQL statement.

Setting up a database

Ask your DBA - database administrator, to do the following:

  1. Create a table named test.
  2. Provide a Username and Password to connect to it.
  3. Get the name of the server.

Setting up the DSN - Data Source Name

You need to create a Data Source Name which identifies the server and the table to which you have to connect.

Do the following steps to set up a DSN:

  1. Go to Control Panel/Administrative Tools/Data Sources(ODBC).
  2. In the User DSN tab, click Add. In the list that appears, select SQL Server and click Finish.
  3. In the first step of the DNS Configuration wizard that pops up, give any name you want to identify your DSN.
  4. Select the server on which the database exists, click Next.
  5. Select the radio button for SQL Server authentication using a Login ID and Password.
  6. In the Client configuration command button, select TCP/IP.
  7. Check the box for 'Connect to SQL Server to obtain default settings' for the additional configuration options.
  8. Provide the Username and Password your DBA has provided, click Next.
  9. Check the box 'Change the default database to' and enter the name of your table.
  10. Accept the defaults and perform the test connection.

Includes

  • windows.h
  • sqlext.h
  • stdio.h
  • string.h

Writing code

Open an empty Win32 console application named SQLtry, add a new CPP file Main. Your Main.cpp looks like this:

int main(void)
{
   HENV   hEnv = NULL; // Env Handle from SQLAllocEnv()
   HDBC   hDBC = NULL; // Connection handle
   HSTMT  hStmt = NULL;// Statement handle
   UCHAR  szDSN[SQL_MAX_DSN_LENGTH] = "Test";// Data Source Name buffer
   UCHAR  szUID[10] = "test";// User ID buffer
   UCHAR  szPasswd[10] = "test";// Password buffer
   UCHAR  szModel[128];// Model buffer
   SDWORD cbModel;// Model buffer bytes recieved
   char   buff[9] = "Testing";
   UCHAR  szSqlStr[128]= "INSERT into (Tablename) (ColumnName) Values ('Testing')" ;

   RETCODE retcode;

  //sprintf((char*)szSqlStr,"INSERT into (Tablename)(Columname) Values ('%s')",buff);
  // Allocate memory for ODBC Environment handle
  SQLAllocEnv (&hEnv);

  // Allocate memory for the connection handle
  SQLAllocConnect (hEnv, &hDBC);

  // Connect to the data source "test" using userid and password.
  retcode = SQLConnect (hDBC, szDSN, SQL_NTS, szUID, SQL_NTS, szPasswd, SQL_NTS);

  if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
  {
      // Allocate memory for the statement handle
      retcode = SQLAllocStmt (hDBC, &hStmt);  

      // Prepare the SQL statement by assigning it to the statement handle
      retcode = SQLPrepare (hStmt, szSqlStr, sizeof (szSqlStr)); 

      // Execute the SQL statement handle
      retcode = SQLExecute (hStmt);    

      // Project only column 1 which is the models
      SQLBindCol (hStmt, 1, SQL_C_CHAR, szModel, sizeof(szModel), &cbModel);

      // Get row of data from the result set defined above in the statement
      retcode = SQLFetch (hStmt);

      // Free the allocated statement handle
      SQLFreeStmt (hStmt, SQL_DROP);

      // Disconnect from datasource
      SQLDisconnect (hDBC);
  }    
            
  // Free the allocated connection handle
  SQLFreeConnect (hDBC);  

  // Free the allocated ODBC environment handle
  SQLFreeEnv (hEnv);

  return 0;
}

Testing Your Code

Perform the following steps:

  1. Open a new database project.
  2. Perform the same steps as you did for setting up the DSN when the wizard pops up.
  3. Click on your table and run the default SQL statement through the toolbar.
  4. You will find the string you sent in the above program in the table.

That's it

Write to me for any queries/suggestions.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Amol Kakhandki

Web Developer

India India

Member

Amol is currently working for a software company in India.His background is an engineering degree in Industrial Electronics.
He has been implementing projects in COM,DCOM,LDAP using VC++ ,MFC,ATL.
This has to be one of my favorite card - Reward Hotel Starwood Preferred Guest Credit Card. Thanks and enjoy!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionAre you sure you're testing your code? Pinmemberbrobert235:49 24 Oct '07  
QuestionCompletely lost on database project Pinmemberbrobert2310:11 23 Oct '07  
Generalhelp or guidance Pinmemberronin_will10:13 10 May '07  
Generalhelp! Pinmembermadhu_USC13:29 20 Nov '05  
QuestionHow can I get the result from "select"? Pinmemberdbyabcxyz12:29 30 Apr '04  
QuestionHow to show the result Pinmembersleeperfung8:40 31 Dec '03  
GeneralThat's pretty good Pinmemberanhtrung0:38 2 Oct '03  
Generalquestion Pinmembers_man10:04 12 Aug '03  
GeneralVB beginner! PinmemberMfon9:05 22 May '02  
Generaldyn. make ODBC connection PinmemberLars Dirks21:34 20 May '02  
GeneralSpeed Difference PinmemberAndrew Bleakley23:30 14 May '02  
GeneralRe: Speed Difference PinmembereXplodus2:15 15 May '02  
Generalquestion PinmembereXplodus20:03 14 May '02  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 14 May 2002
Article Copyright 2002 by Amol Kakhandki
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid