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:
- #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:
- // Connect to ms SQL Server
- // Initialize the pointer
- _ ConnectionPtr pMyConnect = NULL;
- HRESULT hr = pMyConnect. CreateInstance (_ uuidof (Connection ));
- If (FAILED (hr ))
- Return;
- // Initialize the link Parameters
- _ Bstr_t strConnect = "Provider = SQLOLEDB;
- Server = hch;
- Database = mytest;
- Uid = sa; pwd = sa; "; // Database indicates the Database in your system
- // Execute the connection
- Try
- {
- // The Open method connection string must be of the BSTR or _ bstr_t type.
- PMyConnect-> Open (strConnect, "", "", NULL );
- }
- Catch (_ com_error & e)
- {
- MessageBox (e. Description (), "warning", MB_ OK | MB_ICONINFORMATION );
- } // Link Error
C ++ connects to the SQL database step 3 simple data connection
- // Define the _ RecordsetPtr variable and call the Recordset object Open to Open a dataset.
- // The initialization process is as follows:
- _ RecordsetPtr pRecordset;
- If (FAILED (pRecordset. CreateInstance (_ uuidof (Recordset ))))
- {
- Return;
- }
- // Perform the operation
- Try
- {
- PRecordset-> Open (_ variant_t ("userinfo "),
_ Variant_t (IDispatch *) pMyConnect ),
- AdOpenKeyset, adLockOptimistic, adCmdTable );
- }
- Catch (_ com_error & e)
- {
- MessageBox ("Unable to open userinfo table \", "System prompt ",
MB_ OK | MB_ICONINFORMATION );
- }
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
- M_pConnection.CreateInstance (_ uuidof (Connection ));
// Initialize the Connection pointer
- M_pRecordset.CreateInstance (_ uuidof (Recordset ));
// Initialize the Recordset pointer
- CString strSql = "select * from tb_goods"; // The SQL statement to be executed
- 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:
- While (! M_pRecordset-> adoEOF) // traverses and reads records in the name column and outputs
- {
- CString temp = (TCHAR *) (_ bstr_t) m_pRecordset-> GetFields ()-> GetItem
- ("Name")-> Value;
- AfxMessageBox (temp );
- PRecordset-> MoveNext ();
- }
Insert record
- // Remember to initialize the pointer and then perform the following operations
- CString strsql;
- Strsql. Format ("insert into tb_goods (no, name, price)
Values ('% d',' % s', % d) ", m_intNo, m_strName, m_intPrice );
- M_pRecordset = m_pConnection->
Execute (_ bstr_t (strsql), NULL, ad1_text );
Modify record
- CString strsql;
- strsql.Format(”update tb_goods set name=’%s’ ,
price=%d where no=%d “,m_strName,m_intPrice,m_intNo);
- m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText);
Delete record
- CString strsql;
- strsql.Format(”delete from tb_goodswhere no= ‘%d’ “,m_intNo);
- 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.