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:
- Create a table named test.
- Provide a Username and Password to connect to it.
- 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:
- Go to Control Panel/Administrative Tools/Data Sources(ODBC).
- In the User DSN tab, click Add. In the list that appears, select SQL Server and click Finish.
- In the first step of the DNS Configuration wizard that pops up, give any name you want to identify your DSN.
- Select the server on which the database exists, click Next.
- Select the radio button for SQL Server authentication using a Login ID and Password.
- In the Client configuration command button, select TCP/IP.
- Check the box for 'Connect to SQL Server to obtain default settings' for the additional configuration options.
- Provide the Username and Password your DBA has provided, click Next.
- Check the box 'Change the default database to' and enter the name of your table.
- 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; HDBC hDBC = NULL; HSTMT hStmt = NULL; UCHAR szDSN[SQL_MAX_DSN_LENGTH] = "Test"; UCHAR szUID[10] = "test"; UCHAR szPasswd[10] = "test"; UCHAR szModel[128]; SDWORD cbModel; char buff[9] = "Testing";
UCHAR szSqlStr[128]= "INSERT into (Tablename) (ColumnName) Values ('Testing')" ;
RETCODE retcode;
SQLAllocEnv (&hEnv);
SQLAllocConnect (hEnv, &hDBC);
retcode = SQLConnect (hDBC, szDSN, SQL_NTS, szUID, SQL_NTS, szPasswd, SQL_NTS);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
retcode = SQLAllocStmt (hDBC, &hStmt);
retcode = SQLPrepare (hStmt, szSqlStr, sizeof (szSqlStr));
retcode = SQLExecute (hStmt);
SQLBindCol (hStmt, 1, SQL_C_CHAR, szModel, sizeof(szModel), &cbModel);
retcode = SQLFetch (hStmt);
SQLFreeStmt (hStmt, SQL_DROP);
SQLDisconnect (hDBC);
}
SQLFreeConnect (hDBC);
SQLFreeEnv (hEnv);
return 0;
}
Testing Your Code
Perform the following steps:
- Open a new database project.
- Perform the same steps as you did for setting up the DSN when the wizard pops up.
- Click on your table and run the default SQL statement through the toolbar.
- You will find the string you sent in the above program in the table.
That's it
Write to me for any queries/suggestions.