ADOQuery (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of ADO for database connectivity. The example assumes that a TDBGrid is placed on the form.

Code

__fastcall TForm2::TForm2(TComponent* Owner)
	: TForm(Owner)
{
  	/* Login details */
	String UserName = "db_user_name";
	String PassWord = "db_pass_word";
	String Server = "my.db.server";

	/* Connection String */
	String ConnString =
		"Provider=SQLOLEDB.1;Persist Security Info=False;";
	ConnString +=
		"User ID=%s;Password=%s;Data Source=%s;Use Procedure for Prepare=1;";
	ConnString +=
		"Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;";
	ConnString +=
		"Tag with column collation when possible=False";

	/* SQL Query */
	String SQLStr = "SELECT * FROM customer WHERE customer_id = :AnId;";

	/* All ADO variables */
	TADOConnection* ADOConn;
	TADOQuery* ADOQuery;
	TDataSource* DataSrc;
	TParameter* Param;
	/* Create an ADO connection. */
	ADOConn = new TADOConnection(this);

	/* Set up the connection string. */
	ADOConn->ConnectionString = Format(ConnString,
		ARRAYOFCONST((UserName, PassWord, Server)));

	/* Disable login prompt. */
	ADOConn->LoginPrompt = False;

	try
	{
		ADOConn->Connected = true;
	}
	catch (EADOError& e)
	{
		MessageDlg("Error while connecting", mtError,
					  TMsgDlgButtons() << mbOK, 0);
		return;
	}

	/* Create the query. */
	ADOQuery = new TADOQuery(this);
	ADOQuery->Connection = ADOConn;
	ADOQuery->SQL->Add(SQLStr);

	/* Update the parameter that was parsed from the SQL query: AnId. */
	Param = ADOQuery->Parameters->ParamByName("AnId");
	Param->DataType = ftInteger;
	Param->Value = 1;

	/* Set the query to Prepared--it will improve performance. */
	ADOQuery->Prepared = true;

	try
	{
		ADOQuery->Active = true;
	}
	catch (EADOError& e)
	{
		MessageDlg("Error while connecting", mtError,
					  TMsgDlgButtons() << mbOK, 0);
		return;
	}

	/* Create the data source. */
	DataSrc = new TDataSource(this);
	DataSrc->DataSet = ADOQuery;
	DataSrc->Enabled = true;

	/* Finally, initialize the grid. */
	DBGrid1->DataSource = DataSrc;
}

Uses