برای اتصال بـه پایگاه داده اس کیو ال سرور از طریق برنامـه نویسی سی پلاس پلاس نیـاز بـه چند خط کد هست کـه در اینجا چند نمونـه جمع آوری کردیم و مـی توانید از آنـها استفاده کنید.

نمونـه کد اول :

Accessing SQL Server from C++

#define DBNTWIN32
#include <stdio.h>
#include <windows.h>
#include <sqlfront.h>
#include <sqldb.h>

// Forward declarations of the error handler and message handler.

int err_handler(PDBPROCESS, INT, INT, INT, LPCSTR, LPCSTR);
int msg_handler(PDBPROCESS, DBINT, INT, INT, LPCSTR, LPCSTR,
LPCSTR, DBUSMALLINT);
main()
{
PDBPROCESS dbproc; // The connection with SQL Server.
PLOGINREC login; // The login information.
DBCHAR name[100];
DBCHAR city[100];

// Install user-supplied error- and message-handling functions.

dberrhandle (err_handler);
dbmsghandle (msg_handler);

// Initialize DB-Library.

dbinit ();

// Get a LOGINREC.

login = dblogin ();
DBSETLUSER (login, “my_login”);
DBSETLPWD (login, “my_password”);
DBSETLAPP (login, “example”);

// Get a DBPROCESS structure for communication with SQL Server.

dbproc = dbopen (login, “my_server”);

// Retrieve some columns from the authors table in the
// pubs database.
// First, put the command into the command buffer.

dbcmd (dbproc, “SELECT au_lname, city FROM pubs..authors”);
dbcmd (dbproc, ” WHERE state = ‘CA’ “);

// Send the command to SQL Server and start execution.

dbsqlexec (dbproc);

// Process the results.

if (dbresults (dbproc) == SUCCEED)
{

// Bind column to program variables.

dbbind (dbproc, 1, NTBSTRINGBIND, 0, name);
dbbind (dbproc, 2, NTBSTRINGBIND, 0, city);

// Retrieve and print the result rows.

while (dbnextrow (dbproc) != NO_MORE_ROWS)
{
printf (“%s from %s\n”, name, city);
}
}

// Close the connection to SQL Server.

dbexit ();
return (0);
}

int err_handler (PDBPROCESS dbproc, INT severity,
INT dberr, INT oserr, LPCSTR dberrstr, LPCSTR oserrstr)
{
printf (“DB-Library Error %i: ارتباط با sql server با c %s\n”, dberr, dberrstr);
if (oserr != DBNOERR)
{
printf (“Operating System Error %i: %s\n”, oserr, oserrstr);
}
return (INT_CANCEL);
}

int msg_handler (PDBPROCESS dbproc, DBINT msgno, INT msgstate,
INT severity, LPCSTR msgtext, LPCSTR server,
LPCSTR procedure, DBUSMALLINT line)
{
printf (“SQL Server Message %ld: %s\n”, msgno, msgtext);
return (0);
}

نمونـه کد دوم

SqlConnection^ myConnection = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=\"file.mdf\";Integrated Security=True;Connect Timeout=10;User Instance=True"); myConnection->Open(); SqlCommand^ scmd = gcnew SqlCommand("select ID from atable", myConnection); SqlDataReader^ r = scmd->ExecuteReader(); while (r->Read()) __int64 id = r->GetInt64(0); r->Close();

نمونـه کد سوم :

#include "stdafx.h" #include <iostream> #include <windows.h> #include <sqltypes.h> #include <sql.h> #include <sqlext.h> using namespace std; int main() { #define SQL_RESULT_LEN 240 #define SQL_RETURN_CODE_LEN 1000 //define handles and variables SQLHANDLE sqlConnHandle; SQLHANDLE sqlStmtHandle; SQLHANDLE sqlEnvHandle; SQLWCHAR retconstring[SQL_RETURN_CODE_LEN]; //initializations sqlConnHandle = NULL; sqlStmtHandle = NULL; //allocations if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle)) goto COMPLETED; if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) goto COMPLETED; if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle)) goto COMPLETED; //output cout << "Attempting connection to SQL Server..."; cout << "\n"; //connect to SQL Server //I am using a trusted connection and port 14808 //it does not matter if you are using default or named instance //just make sure you define the server name and the port //You have the option to use a username/password instead of a trusted connection //but is more secure to use a trusted connection switch (SQLDriverConnectW(sqlConnHandle, NULL, (SQLWCHAR*)L"DRIVER={SQL Server};SERVER=ServerAddress, 1433;DATABASE=DataBaseName;UID=DataBaseUserName;PWD=PassWord;", //(SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=master;Trusted=true;", SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT)) { case SQL_SUCCESS: cout << "Successfully connected to SQL Server"; cout << "\n"; break; case SQL_SUCCESS_WITH_INFO: cout << "Successfully connected to SQL Server"; cout << "\n"; break; case SQL_INVALID_HANDLE: cout << "Could not connect to SQL Server"; cout << "\n"; goto COMPLETED; case SQL_ERROR: cout << "Could not connect to SQL Server"; cout << "\n"; goto COMPLETED; default: break; } //if there is a problem connecting then exit application if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle)) goto COMPLETED; //output cout << "\n"; cout << "Executing T-SQL query..."; cout << "\n"; //if there is a problem executing the query then exit application //else display query result if (SQL_SUCCESS != SQLExecDirectW(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) { cout << "Error querying SQL Server"; cout << "\n"; goto COMPLETED; } else { //declare output variable and pointer SQLCHAR sqlVersion[SQL_RESULT_LEN]; SQLINTEGER ptrSqlVersion; while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) { SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion); //display query result cout << "\nQuery Result:\n\n"; cout << sqlVersion << endl; } } //close connection and free resources COMPLETED: SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle); SQLDisconnect(sqlConnHandle); SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle); SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle); //pause the console window - exit when key is pressed cout << "\nPress any key to exit..."; getchar(); }

نمونـه کد چهارم :

#include "stdafx.h" //include the below additional libraries #include <iostream> #include <windows.h> #include <sqlext.h> #include <sqltypes.h> #include <sql.h> //use the std namespace using namespace std; int main() { #define SQL_RESULT_LEN 240 #define SQL_RETURN_CODE_LEN 1000 //define handles and variables SQLHANDLE sqlConnHandle; SQLHANDLE sqlStmtHandle; SQLHANDLE sqlEnvHandle; SQLWCHAR retconstring[SQL_RETURN_CODE_LEN]; //initializations sqlConnHandle = NULL; sqlStmtHandle = NULL; //allocations if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle)) goto COMPLETED; if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) goto COMPLETED; if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle)) goto COMPLETED; //output cout << "Attempting connection to SQL Server..."; cout << "\n"; //connect to SQL Server //I am using a trusted connection and port 14808 //it does not matter if you are using default or named instance //just make sure you define the server name and the port //You have the option to use a username/password instead of a trusted connection //but is more secure to use a trusted connection switch (SQLDriverConnect(sqlConnHandle, NULL, //(SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=master;UID=username;PWD=password;", (SQLWCHAR*)L"DRIVER={SQL Server};SERVER=localhost, 1433;DATABASE=master;Trusted=true;", SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT)) { case SQL_SUCCESS: cout << "Successfully connected to SQL Server"; cout << "\n"; break; case SQL_SUCCESS_WITH_INFO: cout << "Successfully connected to SQL Server"; cout << "\n"; break; case SQL_INVALID_HANDLE: cout << "Could not connect to SQL Server"; cout << "\n"; goto COMPLETED; case SQL_ERROR: cout << "Could not connect to SQL Server"; cout << "\n"; goto COMPLETED; default: break; } //if there is a problem connecting then exit application if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle)) goto COMPLETED; //output cout << "\n"; cout << "Executing T-SQL query..."; cout << "\n"; //if there is a problem executing the query then exit application //else display query result if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) { cout << "Error querying SQL Server"; cout << "\n"; goto COMPLETED; } else { //declare output variable and pointer SQLCHAR sqlVersion[SQL_RESULT_LEN]; SQLINTEGER ptrSqlVersion; while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) { SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion); //display query result cout << "\nQuery Result:\n\n"; cout << sqlVersion << endl; } } //close connection and free resources COMPLETED: SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle); SQLDisconnect(sqlConnHandle); SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle); SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle); //pause the console window - exit when key is pressed cout << "\nPress any key to exit..."; getchar(); }

 

. ارتباط با sql server با c . ارتباط با sql server با c ، ارتباط با sql server با c




[اتصال بـه SQL server با سی پلاس پلاس ++C - دیجیتال گروند ارتباط با sql server با c]

نویسنده و منبع | تاریخ انتشار: Sun, 11 Aug 2019 16:51:00 +0000