Connect C ++ to the SQL database in steps

Source: Internet
Author: User

Each programming language has many methods for database operations when applied to program development. I have summarized a lot of online applications that use C ++ to connect to the SQL database without detailed instructions and complete solutions. In addition, due to my limited ability, the written content may have defects.

  • C ++ Dynamic Object Creation Technology
  • C ++ basic application guide for calling python script Functions
  • Introduction to basic concepts of C-style strings in C ++
  • Basic concepts of C ++ string types
  • C ++ parameter transfer

Step 1: System Configuration

1. Set the SQLSERVER server to the SQL logon mode, and set the logon function to "enable" for the sa user in system security. A password is required.

2. you need to configure the data source in ODBC. Select \ "SQL server" as the data source, use "SQL SERVER verification with the user login ID and password entered" for logon, and enter the login name sa) and password. Note that the password cannot be blank, which means that your sa user must have a password. Otherwise, you cannot pass the security policy of the system. The configuration is completed after the test is passed.

C ++ connects to SQL database Step 2 C ++ and SQL connection Initialization

1. Introduce ADO in the stdafx. h header file of your C ++ project.

The Code is as follows:

 
 
  1. #import “c:\Program Files\Common Files\System\ado\msado15.dll” 
    no_namespace rename(”EOF”, “adoEOF”) rename(”BOF”, “adoBOF”) 

2. Define the _ ConnectionPtr variable and call the Open method of the Connection object to establish a Connection with the server.

The Data Type _ ConnectionPtr is actually a specific instance class obtained by the class template _ com_ptr_t. The _ ConnectionPtr class encapsulates the Idispatch interface pointer of the Connection object and some necessary operations. You can use this pointer to manipulate the Connection object.

For example, to connect to the SQLServer database, the Code is as follows:

 
 
  1. // Connect to ms SQL Server
  2. // Initialize the pointer
  3. _ ConnectionPtr pMyConnect = NULL;
  4. HRESULT hr = pMyConnect. CreateInstance (_ uuidof (Connection ));
  5. If (FAILED (hr ))
  6. Return;
  7. // Initialize the link Parameters
  8. _ Bstr_t strConnect = "Provider = SQLOLEDB;
  9. Server = hch;
  10. Database = mytest;
  11. Uid = sa; pwd = sa; "; // Database indicates the Database in your system
  12. // Execute the connection
  13. Try
  14. {
  15. // The Open method connection string must be of the BSTR or _ bstr_t type.
  16. PMyConnect-> Open (strConnect, "", "", NULL );
  17. }
  18. Catch (_ com_error & e)
  19. {
  20. MessageBox (e. Description (), "warning", MB_ OK | MB_ICONINFORMATION );
  21. } // Link Error

C ++ connects to the SQL database step 3 simple data connection

 
 
  1. // Define the _ RecordsetPtr variable and call the Recordset object Open to Open a dataset.
  2. // The initialization process is as follows:
  3. _ RecordsetPtr pRecordset;
  4. If (FAILED (pRecordset. CreateInstance (_ uuidof (Recordset ))))
  5. {
  6. Return;
  7. }
  8. // Perform the operation
  9. Try
  10. {
  11. PRecordset-> Open (_ variant_t ("userinfo "),
    _ Variant_t (IDispatch *) pMyConnect ),
  12. AdOpenKeyset, adLockOptimistic, adCmdTable );
  13. }
  14. Catch (_ com_error & e)
  15. {
  16. MessageBox ("Unable to open userinfo table \", "System prompt ",
    MB_ OK | MB_ICONINFORMATION );
  17. }

Step 4 of connecting C ++ to the SQL database

Here is the key. I think that as long as you know SQL statements, everything will be easier and more efficient than the above methods.

First

 
 
  1. M_pConnection.CreateInstance (_ uuidof (Connection ));
    // Initialize the Connection pointer
  2. M_pRecordset.CreateInstance (_ uuidof (Recordset ));
    // Initialize the Recordset pointer
  3. CString strSql = "select * from tb_goods"; // The SQL statement to be executed
  4. M_pRecordset = m_pConnection-> Execute (_ bstr_t (strSql ),
    NULL, adCmdText); // import the query data to the m_pRecordset data container

Now that your SQL statement has been executed, the data in m_pRecordset is the result of your execution.

Retrieve records:

 
 
  1. While (! M_pRecordset-> adoEOF) // traverses and reads records in the name column and outputs
  2. {
  3. CString temp = (TCHAR *) (_ bstr_t) m_pRecordset-> GetFields ()-> GetItem
  4. ("Name")-> Value;
  5. AfxMessageBox (temp );
  6. PRecordset-> MoveNext ();
  7. }

Insert record

 
 
  1. // Remember to initialize the pointer and then perform the following operations
  2. CString strsql;
  3. Strsql. Format ("insert into tb_goods (no, name, price)
    Values ('% d',' % s', % d) ", m_intNo, m_strName, m_intPrice );
  4. M_pRecordset = m_pConnection->
    Execute (_ bstr_t (strsql), NULL, ad1_text );

Modify record

 
 
  1. CString strsql;  
  2. strsql.Format(”update tb_goods set name=’%s’ , 
    price=%d where no=%d “,m_strName,m_intPrice,m_intNo);   
  3. m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText); 

Delete record

 
 
  1. CString strsql;  
  2. strsql.Format(”delete from tb_goodswhere no= ‘%d’ “,m_intNo);  
  3. m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText); 

These are several common SQL statements and execution methods. Efficiency may not be high, but it is easy to understand. If you are familiar with SQL statements, you can execute queries more effectively and directly obtain the required records. This section describes how to connect C ++ to the SQL database.

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.