Job Recruitment Website - Ranking of immigration countries - How to connect SQL database with C++?
How to connect SQL database with C++?
You can leave a mailbox if necessary. I have some documents for beginners that I can send to you. Very good. I hope to continue to work hard. Interview, then everything will be a cloud. . . Haha)
Basic process
The hardest part is actually in the beginning For beginners of any new technology, the most important thing is to "get started" and master its main points. Let's take a look at the basic process of ADO database development!
(1) Initializes the COM library and introduces the ADO library definition file.
(2) Connect the database with the connection object.
(3) Using the established Connection, execute SQL commands through the connection and command objects, or use the Recordset object to obtain the result record set for query and processing.
(4) Close the connection and release the object after use.
Preparatory work:
In order to test the example provided in this article, we use the Access database, and you can also find this test.mdb directly in the sample code provided by us.
Below we will introduce the above steps in detail and give the relevant code.
Initialization of 1COM library
We can use AfxOleInit () to initialize the COM library, which is usually done in the overloaded function of CWinApp::InitInstance (). Please look at the following code:
BOOL cado test 1 app::init instance()
{
AfxOleInit();
......
2 Introduce ADO type library with #import instruction
Let's add the following sentence to stdafx.h: (Where can I find this file? You can find it in the header file of the file view)
# import " c:\ program files \ common files \ system \ ado \ msado 15 . dll " no _ namespace rename(" EOF "," adoEOF ")
What does this sentence do? Its final function is similar to the familiar #include. When compiling, the system will generate two C++ header files, MSADO 15. TLH and ADO 15. TLI to define ADO libraries.
Some precautions:
(1) The msado 15.dll in your environment may not be in this directory, please modify it according to the actual situation.
(2) When compiling, the following warning may appear. Microsoft explained this in MSDN and suggested that we ignore this warning.
Msado 15.tlh(405): Warning C4 146: The unary subtraction operator is applied to unsigned types, and the result is still unsigned.
3 Create a connection object and connect to the database.
First, we need to add a pointer to the connection object:
_ ConnectionPtr m _ pConnection
The following code demonstrates how to create a connection object instance and how to connect to a database and catch an exception.
BOOL cado test 1 DLG::OnInitDialog()
{
CDialog::OnInitDialog();
HRESULT hr
attempt
{
Hr = m _ connection. CreateInstance("ADODB。 Connection "); ///Create a connection object
If (Success (hours))
{
Hr = m _ connection-> Open("Provider=Microsoft。 Jet. OLEDB.4.0 data source =test.mdb ","","",admodeunknown); ///Connect to the database
///The provider in the connection string in the above sentence is for the ACCESS2000 environment. For ACCESS97, it needs to be changed to: provider = Microsoft. jet . oledb . 3.5 1;
}
}
Catch(_ com _ errore)////catch an exception.
{
CString errormessage
Error message. Format ("Failed to connect to the database! \ r \ Error message: %s ",e.errormessage ());
AfxMessageBox(error message); ///Display an error message
}
In this code, we connect to the database through the Open method of the Connection object. The following is the prototype of this method.
Hresult connection15:: open (_ bstr _ tconnectionstring, _ bstr _ tuseid, _bstr_t Password, long option)
ConnectionString is the connection string, UserID is the user name, Password is the login password, and Options is the connection option, which is used to specify the permission of the connection object to update data.
Options can be the following constants:
AdModeUnknown: default. The current permission is not set.
AdModeRead: read-only
AdModeWrite: write only.
AdModeReadWrite: you can read and write.
AdModeShareDenyRead: Prevents other connection objects from opening connections with read permission.
AdModeShareDenyWrite: Prevents other connection objects from opening connections with write permission.
AdModeShareExclusive: Prevents other connection objects from opening connections with read and write permissions.
AdModeShareDenyNone: Prevents other connection objects from opening connections with any permissions.
We give some common connection methods for your reference:
(1) connects to the ACCESS2000 database through the JET database engine.
M _ connection-> Open("Provider=Microsoft。 Jet. OLEDB.4.0 data source =C:\\test.mdb ","","",admodeunknown);
(2) Connect any database supporting ODBC through DSN data source:
M _ connection-> open(" Data Source = adotest; UID = saPWD =; ”,"","",admode unknown);
(3) Connect to the SQL SERVER database without DSN:
M _ connection-> open(" driver = { SQL Server }; Server =127.0.0.1; DATABASE = vckbaseUID = saPWD= 139 ","","",admode unknown);
Where Server is the name of the SQL server and DATABASE is the name of the library.
In addition to the Open method, there are many methods in the Connection object. Let's first introduce two useful properties in the connection object, ConnectionTimeOut and State.
ConnectionTimeOut is used to set the timeout of the connection and needs to be called before opening, for example:
M _ connection-> connection time out = 5; ///Set the timeout to 5 seconds.
M _ connection-> open(" Data Source = adotest;" ,"","",admode unknown);
The State property indicates the state of the currently connected object, 0 means closed, and 1 means open. We can read this property to make corresponding processing, such as:
If(m _ p connection->; Status)
M _ connection-> close(); ///If the connection is already open, please close it.
-
Oh, by the way, I haven't done VC before, so this time the boss has a project to do, and I can't help it! ! Ask more questions later! !
-
You don't understand a lot of basics now, and it's a little difficult to get up even the database.
-
If you use vc6, right-click the control to which you want to add variables, and select the classwizard and member variables tabs, which will automatically point to the control to which you want to add variables. Just click Add Variable and name it.
-
My point is that I don't know how to add corresponding variables to the control! ! Please be clear! !
-
What is CBaseEditBox? Don't define it like this. You should first put the control on the dialog box form, and then add the corresponding variable to this control, so that VC will automatically associate the control with the variable.
-
I just got it. It's not good. Please make it clear! ! !
I want to put the records read from the database in a text box!
Then put an edit box on the interface.
I added variables to the C***Dlg class.
Public:
CBaseEditBox m_list
Next, I connect to the database in the onOK event of the button, and I want to put the obtained records in the m_list.
//Read the fields in the library and add them to the list box.
And (! m _ pRecordset-& gt; adoEOF)
{
Var = m_pRecordset->GetCollect ("user name");
if(var.vt! = VT_NULL)
strName =(LPCSTR)_ bstr _ t(var);
var = m_pRecordset->get collect(" Password ");
if(var.vt! = VT_NULL)
strAge =(LPCSTR)_ bstr _ t(var);
m_list。 AddString(strName+"->; +strAge);
m _ pRecordset-& gt; MoveNext();
}
//The default list points to the first item, and the record pointer is moved and displayed at the same time.
m_list。 SetCurSel(0);
Then there are many mistakes:
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG.h (18): Error C2 146: Syntax Error: Missing ";" Before the identifier "m_list"
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG.h (18): Error C250 1: "CBaseEditBox ":Missing storage class or type descriptor.
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG.h (18): Error C250 1: "m_list ":Missing storage class or type descriptor.
TestADODlg.cpp
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG.h (18): Error C2 146: Syntax Error: Missing ";" Before the identifier "m_list"
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG.h (18): Error C250 1: "CBaseEditBox ":Missing storage class or type descriptor.
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG.h (18): Error C250 1: "m_list ":Missing storage class or type descriptor.
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG. CPP (195): Error C2065: "m _ list": Undeclared identifier.
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG. CPP (195): Error C2228: located at. AddString' must have class/structure/union type.
D: \ Microsoft Visual Studio \ My Projects \ Testado \ Testado DLG. CPP (201): Left side of error C2228: SetCurSel' must have a class/structure/union type.
generating code ...
An error occurred while executing cl.exe.
What is the reason?
-
/document/viewdoc/? id=496
Replace the statement connecting access in the article with:
Connect to SQL database:
M _ connection-> open(" Provider = SQL oledb . 1; Server =192.168.1.6; Database = mysqlUID = saPWD =;; ”,"","",admode unknown);
Where Server is the name of the SQL server and DATABASE is the name of the library.
- Related articles
- What is the sign of dreaming of going abroad?
- Jet Li's will was made public: Donate 1 billion yuan to return to his nationality. Why did Jackie Chan's 7-word reply make him cry?
- How to understand the new situation of education
- What was the name of Chongqing fengjie county before? Why did it change its name to fengjie county (the origin of Fengjie)?
- I graduated from China, and now I apply to immigrate to the United States. What should I do if I want to continue my studies after I arrive in the United States?
- Why did you immigrate to Spain?
- Which city is the only city in China without rural areas?
- Nova Scotia, are there many people in China? I heard that Captain University has a lot of things about China people, right? Will more immigrants be very competitive?
- What are the tourism resources in Yunnan? What are the characteristics of Yunnan's tourism resources?
- And Dutch marriage immigrants.