Connect C ++ to Oracle

Source: Internet
Author: User

I have just learned C ++, and I feel like I have learned something faster!

The following is the code of a small program connecting to Oracle using ADO ......

First, configure Oracle, find the Oracle \ network \ ADMIN \ tnsnames. ora file in the Oracle installation path, and configure the connection configuration.


[Plain]
BOSS =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP) (HOST = xx. xx) (PORT = 1521 ))
)
(CONNECT_DATA =
(SERVICE_NAME = boss)
)
)

BOSS =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP) (HOST = xx. xx) (PORT = 1521 ))
)
(CONNECT_DATA =
(SERVICE_NAME = boss)
)
) Create a new header file named CDBOperation. h:


[Cpp]
# Pragma once
# Import "c: \ program files \ common files \ system \ ado \ msado15.dll" no_namespace rename ("EOF", "adoEOF ")
Class CDBOperation
{
Public:
// Initialize the objects required for database operations
CDBOperation (void );
~ CDBOperation (void );
 
// Connect to the database
Bool ConnToDB (char * ConnectionString, char * UserID, char * Password );
 
// Database operation functions
// Query operation deletion and Addition
_ RecordsetPtr ExecuteWithResSQL (const char *);
 
Private:
Void PrintErrorInfo (_ com_error &);
 
Private:
// Initialize database connections, commands, and Record Sets
_ ConnectionPtr CreateConnPtr ();
_ CommandPtr createcommp tr ();
_ RecordsetPtr CreateRecsetPtr ();
 
Private:
// Connection and command operation objects required for database connection
_ ConnectionPtr m_pConnection;
_ CommandPtr m_pCommand;
};

# Pragma once
# Import "c: \ program files \ common files \ system \ ado \ msado15.dll" no_namespace rename ("EOF", "adoEOF ")
Class CDBOperation
{
Public:
// Initialize the objects required for database operations
CDBOperation (void );
~ CDBOperation (void );

// Connect to the database
Bool ConnToDB (char * ConnectionString, char * UserID, char * Password );

// Database operation functions
// Query operation deletion and Addition
_ RecordsetPtr ExecuteWithResSQL (const char *);

Private:
Void PrintErrorInfo (_ com_error &);

Private:
// Initialize database connections, commands, and Record Sets
_ ConnectionPtr CreateConnPtr ();
_ CommandPtr createcommp tr ();
_ RecordsetPtr CreateRecsetPtr ();

Private:
// Connection and command operation objects required for database connection
_ ConnectionPtr m_pConnection;
_ CommandPtr m_pCommand;
}; Create a c ++ source file named CDBOperation. cpp:
[Cpp]
# Include "stdafx. h"
# Include "DBOperation. h"
CDBOperation: CDBOperation (void)
{
CoInitialize (NULL );
M_pConnection = CreateConnPtr ();
M_pCommand = createcomatrix tr ();
}
CDBOperation ::~ CDBOperation (void)
{
M_pConnection-> Close ();
}
Bool CDBOperation: ConnToDB (char * ConnectionString, char * UserID, char * Password)
{
If (NULL = m_pConnection)
{
Printf ("Failed to create connection \ n ");
Return false;
}
Try
{
HRESULT hr = m_pConnection-> Open (ConnectionString, UserID, Password, NULL );
If (TRUE = FAILED (hr ))
{
Return false;
}
M_pCommand-> ActiveConnection = m_pConnection;
Return true;
}
Catch (_ com_error & e)
{
PrintErrorInfo (e );
Return false;
}
}
_ RecordsetPtr CDBOperation: ExecuteWithResSQL (const char * SQL)
{
Try
{
M_pCommand-> CommandText = _ bstr_t (SQL );
_ RecordsetPtr pRst = m_pCommand-> Execute (NULL, NULL, ad1_text );
Return pRst;
}
Catch (_ com_error & e)
{
PrintErrorInfo (e );
Return NULL;
}
}
Void CDBOperation: PrintErrorInfo (_ com_error & e)
{
Printf ("Error infomation are as follows \ n ");
Printf ("ErrorNo: % d \ nError Message: % s \ nError Source: % s \ nError Description: % s \ n", e. error (), e. errorMessage (), (LPCTSTR) e. source (), (LPCTSTR) e. description ());
}
 
_ ConnectionPtr CDBOperation: CreateConnPtr ()
{
HRESULT hr;
_ ConnectionPtr connPtr;
Hr = connPtr. CreateInstance (_ uuidof (Connection ));
If (FAILED (hr) = TRUE)
{
Return NULL;
}
Return connPtr;
}
 
_ CommandPtr CDBOperation: createcommp tr ()
{
HRESULT hr;
_ CommandPtr commp TR;
Hr = commp tr. CreateInstance (_ uuidof (Command ));
If (FAILED (hr) = TRUE)
{
Return NULL;
}
Return commp TR;
}
 
_ RecordsetPtr CDBOperation: CreateRecsetPtr ()
{
HRESULT hr;
_ RecordsetPtr recsetPtr;
Hr = recsetPtr. CreateInstance (_ uuidof (Command ));
If (FAILED (hr) = TRUE)
{
Return NULL;
}
Return recsetPtr;
}

# Include "stdafx. h"
# Include "DBOperation. h"
CDBOperation: CDBOperation (void)
{
CoInitialize (NULL );
M_pConnection = CreateConnPtr ();
M_pCommand = createcomatrix tr ();
}
CDBOperation ::~ CDBOperation (void)
{
M_pConnection-> Close ();
}
Bool CDBOperation: ConnToDB (char * ConnectionString, char * UserID, char * Password)
{
If (NULL = m_pConnection)
{
Printf ("Failed to create connection \ n ");
Return false;
}
Try
{
HRESULT hr = m_pConnection-> Open (ConnectionString, UserID, Password, NULL );
If (TRUE = FAILED (hr ))
{
Return false;
}
M_pCommand-> ActiveConnection = m_pConnection;
Return true;
}
Catch (_ com_error & e)
{
PrintErrorInfo (e );
Return false;
}
}
_ RecordsetPtr CDBOperation: ExecuteWithResSQL (const char * SQL)
{
Try
{
M_pCommand-> CommandText = _ bstr_t (SQL );
_ RecordsetPtr pRst = m_pCommand-> Execute (NULL, NULL, ad1_text );
Return pRst;
}
Catch (_ com_error & e)
{
PrintErrorInfo (e );
Return NULL;
}
}
Void CDBOperation: PrintErrorInfo (_ com_error & e)
{
Printf ("Error infomation are as follows \ n ");
Printf ("ErrorNo: % d \ nError Message: % s \ nError Source: % s \ nError Description: % s \ n", e. error (), e. errorMessage (), (LPCTSTR) e. source (), (LPCTSTR) e. description ());
}

_ ConnectionPtr CDBOperation: CreateConnPtr ()
{
HRESULT hr;
_ ConnectionPtr connPtr;
Hr = connPtr. CreateInstance (_ uuidof (Connection ));
If (FAILED (hr) = TRUE)
{
Return NULL;
}
Return connPtr;
}

_ CommandPtr CDBOperation: createcommp tr ()
{
HRESULT hr;
_ CommandPtr commp TR;
Hr = commp tr. CreateInstance (_ uuidof (Command ));
If (FAILED (hr) = TRUE)
{
Return NULL;
}
Return commp TR;
}

_ RecordsetPtr CDBOperation: CreateRecsetPtr ()
{
HRESULT hr;
_ RecordsetPtr recsetPtr;
Hr = recsetPtr. CreateInstance (_ uuidof (Command ));
If (FAILED (hr) = TRUE)
{
Return NULL;
}
Return recsetPtr;
} My code is placed in a button Click event of MFC:

Remember to import the header file # include "DBOperation. h" to the cpp file that handles the event"


[Cpp]
CDBOperation dbOper;
Bool bConn = dbOper. ConnToDB ("Provider = OraOLEDB. Oracle.1; Persist Security Info = True; Data Source = boss", "User Name", "password ");
If (false = bConn)
{
MessageBox (LPCTSTR) "An error occurred while connecting to the database \ 0 );
Return;
}
 
// Query
_ RecordsetPtr pRst;
Char SQL [255] = {0 };
Strcpy (SQL, "select * from boss_test_table2 where rownum = 1 ");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL = pRst)
{
MessageBox (_ T ("An error occurred while querying data! \ 0 "), 0, 0 );
Return;
}
If (pRst-> adoEOF)
{
PRst-> Close ();
MessageBox (LPCTSTR) "There is no records in this table \ 0", 0, 0 );
Return;
}
_ Variant_t vSno, vName;
While (! PRst-> adoEOF)
{
// PRst-> MoveFirst (); // the record set pointer moves to the front of the query result set
VSno = pRst-> GetCollect (_ variant_t ("U_NUMBER "));
VName = pRst-> GetCollect (_ variant_t ("USERS_NAME "));
MessageBox (LPCTSTR) (_ bstr_t) vSno, 0, 0 );
PRst-> MoveNext ();
}
 
Strcpy (SQL, "insert into boss_test_table2 (u_number, users_name, users_phone, status, customno_id) values ('123', 'C + TTT + ', '123', 2, 'ppppppppup ')");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL! = PRst)
{
AfxMessageBox (_ T ("data inserted successfully \ n "));
}
// Execute the delete statement
Sprintf (SQL, "delete boss_test_table2 where u_number = '% S'", "009 ");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL! = PRst)
{
MessageBox (_ T ("data deleted successfully \ 0"), 0, 0 );
}
// Execute the update statement
Sprintf (SQL, "update boss_test_table2 set users_name = '% S'", "C ++ anti-human, MFC anti-social ");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL! = PRst)
{
MessageBox (_ T ("data updated successfully \ 0"), 0, 0 );
}

CDBOperation dbOper;
Bool bConn = dbOper. ConnToDB ("Provider = OraOLEDB. Oracle.1; Persist Security Info = True; Data Source = boss", "User Name", "password ");
If (false = bConn)
{
MessageBox (LPCTSTR) "An error occurred while connecting to the database \ 0 );
Return;
}

// Query
_ RecordsetPtr pRst;
Char SQL [255] = {0 };
Strcpy (SQL, "select * from boss_test_table2 where rownum = 1 ");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL = pRst)
{
MessageBox (_ T ("An error occurred while querying data! \ 0 "), 0, 0 );
Return;
}
If (pRst-> adoEOF)
{
PRst-> Close ();
MessageBox (LPCTSTR) "There is no records in this table \ 0", 0, 0 );
Return;
}
_ Variant_t vSno, vName;
While (! PRst-> adoEOF)
{
// PRst-> MoveFirst (); // the record set pointer moves to the front of the query result set
VSno = pRst-> GetCollect (_ variant_t ("U_NUMBER "));
VName = pRst-> GetCollect (_ variant_t ("USERS_NAME "));
MessageBox (LPCTSTR) (_ bstr_t) vSno, 0, 0 );
PRst-> MoveNext ();
}

Strcpy (SQL, "insert into boss_test_table2 (u_number, users_name, users_phone, status, customno_id) values ('123', 'C + TTT + ', '123', 2, 'ppppppppup ')");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL! = PRst)
{
AfxMessageBox (_ T ("data inserted successfully \ n "));
}
// Execute the delete statement
Sprintf (SQL, "delete boss_test_table2 where u_number = '% S'", "009 ");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL! = PRst)
{
MessageBox (_ T ("data deleted successfully \ 0"), 0, 0 );
}
// Execute the update statement
Sprintf (SQL, "update boss_test_table2 set users_name = '% S'", "C ++ anti-human, MFC anti-social ");
PRst = dbOper. ExecuteWithResSQL (SQL );
If (NULL! = PRst)
{
MessageBox (_ T ("data updated successfully \ 0"), 0, 0 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.