Simple use of SQL Server Express in VS2010 Win32 Program (c + +)

Source: Internet
Author: User
Tags win32 sql server express visual studio 2010

Because the short semester job needs to join the database in the previous program's server, it is easy to learn the vs2010 of the database sqlsever2008, the learning process is not very smooth, in the online did not find a special complete tutorial, now the course is over, specially to write a, to facilitate the children of the back of the paper, Because I also learn half understand, if there is anything wrong place also please correct me!

One, start from scratch, build a database

(1) Open VS2010, tools, connect to the database, and then in the dialog box that pops up, select Microsoft SQL Server, click Continue

(2) In the dialog box shown in "Server name", enter "own computer name \SQLExpress", such as "Disturbance-pc\sqlexpress", click "OK". You can also click the Test Connection button to test and a dialog box prompts you.

(3) before using VS2010 when everyone should have seen something called "Server Explorer", anyway, I have noticed, but do not know what it is to do, now know is to manage the database used. After performing the above operation should have been connected to the default master database, you can click the right mouse button to add a table or other things, there is not much to say.

(4) If you are not successful, the SQL Server component may not be installed when you install Visual Studio. Simply rerun the setup program for Visual Studio, select Change or remove Microsoft Visual Studio 2010, click Next, and then click Add or Remove features to make sure that the Microsoft SQL Server 2008 Express Studio ".

(5) The SQL Server service is now started by default. If you accidentally stop it manually, you can run SQL Server Configuration Manager to start it (you can find it in the Start menu).

Second, the completion of the creation of the database, we first thought is how to connect it in the program, here we use the method of ADO to connect.

(1) ADO using the Step method:

1. Initialize the COM library and introduce the ADO library definition file

2. Connect to the database with the Connection object

3. Use established connections, execute SQL commands through connection, command objects, or use Recordset objects to obtain result recordsets for querying, processing

4. Close the connection release object after use is complete

(2) Specific operation:

1. Add the header file CADO.h, where the path of the import to be based on their own computer system to determine, anyway find msado15.dll can be.

1 #pragmaOnce2#import"C:\Program Files (x86) \common Files\system\ado\msado15.dll"No_namespace Rename ("EOF","adoeof")3#include <icrsint.h>4 classCado5 {6  Public:7Cado (void);8~cado (void);9 _connectionptr m_pconnection;Ten _recordsetptr M_precordset; One     voidConnect (void); A     voidExitconnect (void); -_recordsetptr&GetRecordSet (_bstr_t SQL); -};

2. Add CADO.cpp, where m_pconnection->connectionstring the connection string after the determination to determine according to their own computer, later will talk about how to get the connection string, I started because I could not find the correct connection string, wasted a lot of time.

1#include"ADO.h"2#include <iostream>3 using namespacestd;4 5Cado::cado (void)6 {7 }8 9 TenCado::~cado (void) One { A } -  - voidCado::connect (void) the {  -     Try{ -CoInitialize (NULL);//Initializing the COM environment -M_pconnection.createinstance ("ADODB. Connection");//Create a Connection object +m_pconnection->connectionstring="provider=sqloledb.1;integrated Security=sspi; Persist Security Info=false; User id=test;initial catalog=userinfo1;data source=disturbance-pc\\sqlexpress";  -HRESULT Hr=m_pconnection->open ("","","", adModeUnknown); +         if(hr!=S_OK) Acout<<"Can not connect to the specified database!"<<Endl; at     } -     Catch(_com_error e) { -Cout<<e.description () <<Endl; -     } - } - voidCado::exitconnect (void) in { -     if(m_precordset!=NULL) { toM_precordset->Close (); +M_pconnection->Close (); -     } the:: CoUninitialize ();//Releasing the Environment * } $ Panax Notoginseng_recordsetptr&Cado::getrecordset (_bstr_t SQL) - { them_precordset=NULL; + Cado link; A     Try{ the         if(m_pconnection==NULL) + Connect (); - m_precordset.createinstance (__uuidof (Recordset)); $M_precordset->Open ((_bstr_t) SQL, M_pconnection.getinterfaceptr (), adopendynamic, adLockOptimistic, adCmdText); $     } -     Catch(_com_error e) { -Cout<<e.description () <<Endl; them_precordset=NULL; -         returnM_precordset;Wuyi     } the     returnM_precordset; -}

3. There are several considerations for database operations in the main function

(1). to M_precordset=record. GetRecordSet (bstr_t); This sentence, always do not know what the return value is, then found that you can interpret it as a pointer to the first line of the data you are looking for to meet the criteria, we only need to cooperate with M_precordset->movenext (); Moving down one line allows you to traverse the entire table, and M_precordset->putcollect and M_precordset->getcollect can access the data for the specific column of the current row separately, knowing that You can complete some basic operation of the database, if you need more functions, please Baidu ADO operation function.

(2). M_precordset->getcollect The type returned is _variant_t, for string type data items, to be cast with CString (), I tried a lot of methods on the Web to turn char* are not successful, This problem also wasted a lot of time, if you have any method of words must share ha.

1#include <afxwin.h>2#include <iostream>3#include"ADO.h"4#include <string>5 using namespacestd;6 7 voidMain ()8 {9 Ten     stringSQL; One Cado record; A record. Connect (); - _recordsetptr M_precordset; -Sql="SELECT * from UserInfo";//This sentence means finding the location of the table UserInfo in the database the _bstr_t bstr_t (Sql.c_str ()); -M_precordset=record. GetRecordSet (bstr_t);//The returned can be assumed to be a pointer that points to the first row of the table -      -     //M_precordset->movefirst (); //move to the first record +      while(!m_precordset->adoeof) { -M_precordset->delete (adaffectcurrent);//Delete current record +M_precordset->movenext ();//move to the next line A     } at  - _variant_t vusername,vbirthday,vid,vold; -      for(intI=0;i<3; i++)//add three new records and assign values -     { -M_precordset->addnew ();//add a new record -M_precordset->putcollect ("School Number", _variant_t (int) (i+Ten))); inM_precordset->putcollect ("name", _variant_t ("Adasa")); -M_precordset->putcollect ("Age", _variant_t (int) +)); toM_precordset->putcollect ("Birthday", _variant_t ("1930-3-15")); +     } -M_precordset->update ();//save to Library, corresponding to AddNew the  *M_precordset=record. GetRecordSet (bstr_t);//get the first row of pointers again $      while(!m_precordset->adoeof)Panax Notoginseng     { -VID = M_precordset->getcollect (_variant_t (Long)0));//gets the value of column 1th, starting from 0, you can also give the name of the dequeue directly, as in the next line thevUserName = M_precordset->getcollect ("name");//gets the value of the Last Name field +VOld = M_precordset->getcollect ("Age"); AVbirthday = M_precordset->getcollect ("Birthday"); theprintf"id:%d, Name:%s, Age:%d, Birthday:%s\r\n", + Vid.lval, - CString (vusername.bstrval), $ Vold.lval, $CString (Vbirthday.bstrval));//The Output window in debug mode outputs the record in the recordset -M_precordset->movenext ();//move to the next record -     } the record. Exitconnect (); -}

Third, access to the connection string

Do not underestimate this string, if there is no correct method, but really that it does not do AH!! Here is a direct copy of the method found online:

Create any new TXT file and rename it to. x.udl. Then double-click the file, and the Database Connection Properties window appears. The first tab "provider" lists all database engines, Access, SQL Server, Oracle, etc., select the next step to jump to the second tab "Connection", select the Server Name field can fill in the server's IP address, the machine will not fill or fill the dot (i filled out here) Your computer name \sqlexpress "to connect"); After you fill in the database user name and password, you can select the database. Click the "Test Connection" button to succeed. Are you sure. Open x.udl with Notepad. You will see the connection string it generates. As follows:

"Provider=sqloledb.1;integrated Security=sspi; Persist Security Info=false; User id=test;initial catalog=userinfo1;data source=disturbance-pc\\sqlexpress ";

In this connection string, the Persist Security info property is true to indicate that the password is still saved after the connection is established and generally false. The ID and Password properties will only be available if you check "Allow Save password" in the Database Properties dialog box above. You can add them manually. Cfdata is the name of my database.

PS: If there is a ' \ ' sign inside the connection string, write ' \ \ ', otherwise the problem will be escaped.

So far the merit has become, the step is very few wow.

The whole tutorial refers to a lot of other people's Code and tutorials, hoping to help everyone put ^ ^

Forwarding please indicate the source: http://www.cnblogs.com/SolarWings/

Refer to the link:

1. Use the VS2010 internal Database sqlserver2008
Http://bbs.cfan.com.cn/thread-1530883-1-1.html

2. Connect to the database in the Win32 program
Http://www.cnblogs.com/littlex/archive/2012/07/03/2574782.html

3. The connection string in the previous step will be problematic, see the correct method
http://blog.csdn.net/asanscape/article/details/6084600

Related Article

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.