VC accesses the database (and the data source browsing window pops up to interact with users)

Source: Internet
Author: User
VC database access

ArticleCategory: C ++ Programming

ODBC (Open Database Connectivity) is a database access standard defined by Microsoft. It provides a standard database access method to access databases of different database providers, it is essentially a group of database access APIs. although there are many ways to access databases, ODBC is widely used in actual programming because of its relatively simple programming.
VC ++ provides a set of mfc odbc classes that encapsulate ODBC APIs to reduce Program Code Write volume. When you use the mfc odbc class in VC ++ to access the database, you usually first configure or select an existing data source, and then construct a cdatabase class object to open the data source, the Database Class Object and SQL (Structured Query Language) can be used to access the database, and then the crecordset class or its inherited class object can be constructed, you can use dataset objects and SQL statements to operate tables in the database. In VC ++, using the mfc odbc class to operate SQL Server databases is basically the same idea.

1. Configure the data source

In a program, dynamic configuration of the data source based on the user's choice without calling the ODBC data source Manager is sometimes necessary for application development. After all, the ODBC data source Manager is complex for users who are not familiar with the database, and the interface style of the ODBC data source Manager may be different from that of the entire application, for rigorous application developers, these are intolerable.

When configuring the SQL server data source, you must have the SQL Server server name and the target database name on the server (otherwise, the configuration data source dialog box or failure will pop up when you open the data source ). This is different from specifying the path of the database file When configuring access and other database data sources.

You can use the odbc api function sqlbrowseconnect to obtain the database and language information of all local SQL Server servers and servers. The usage is as follows:

① Obtain the server name

Sqlbrowseconnect (hdbc, "driver = {SQL Server};", SQL _ets, browseresult, sizeof (browseresult), & browseresultlen );

Hdbc is the link handle obtained by using the sqlallochandle function. The second parameter is the input string specifying the link attribute, the third parameter is the length of the input string, and the fourth parameter is the pointer of the output string, the information we get is stored in this string. The fifth parameter specifies the length of the output string, and the sixth parameter indicates the length of the actually returned string. The string returned by the function pointed to by browseresult contains the format "server: Server = {server_name1, server_name2 ,...}" Server_name1 and server_name2 are SQL Server names.

② Obtain the Database Name

After you select a server, you can use the sqlbrowseconnect function to obtain the database or language information on the server (if necessary ).

Sqlbrowseconnect (hdbc, "Server = server_name1; uid = sa; Pwd = 515578;", SQL _cnt, browseresult, sizeof (browseresult), & browseresultlen );

UID and PWD are the usernames and passwords used to access the server. The string returned by the function directed to this browseresult contains a string such as database: Database = {master, model ,...} And language: Language = {Arabic, Brazilian, English ,...} The master and model are the database names on the server.

You can use this information to configure the SQL Server Data source:

Sqlconfigdatasource (null, odbc_add_dsn, "SQL Server", "DSN = mydsn \ 0 Server = xhm \ 0 database = pubs \ 0 \ 0 "))

The author has the honor to find the csqlinfoenumerator class written by Santosh Rao on the Internet, which has three member functions: enumeratesqlservers, enumeratedatabase, and handler. It encapsulates the sqlbrowseconnect function and processes the corresponding characters, this greatly simplifies the use of sqlbrowseconnect functions.

2. Establish a connection with the data source

If you use odbc api functions for connection, both sqlconnect, sqldriverconnect, and sqlbrowseconnect functions can be implemented. The sqlconnect function is used to directly establish a connection with the data source given all parameters. sqldriverconnect is used to specify some connection parameters and pop up the data source browsing window to interact with users, after obtaining enough parameters, establish a connection with the data source. sqlbrowseconnect gets the connection parameters through iteration and then connects them. The usage is described above.

MFC provides a database-type cdatabase for connecting to the data source, through which we can easily establish a connection with the Data source:

// M_db is the cdatabase object

// M_szuserid and m_szpassword are cstring objects. They are the user name and password used to access the data source.

Cstring STR;

STR = _ T ("DSN = xhmtest; uid =") + m_szuserid + _ T ("; Pwd =") + m_szpassword;

If (! M_db.openex (STR, cdatabase: noodbcdialog )){

Afxmessagebox ("failed to open the data source ");

}

In addition, if you want to operate the data source, you can use the opened cdatabase object to execute SQL statements. Create a new table:
STR = "create table tabledemo (column1text, column2 number )";

M_db.executesql (ssql );

3. Obtain the structure information of the database.

In VC ++, you can use the odbc api alone to obtain the structure information of the database. However, the method is very complex and various parameters are not easy to understand, and the returned results are not easy to obtain. In MFC, no separate classes are provided for application developers to obtain database structure information. However, we can still obtain the structure information of the database through some existing methods.

3.1 obtain the table in the database

The odbc api function sqltables can be used to obtain table information in the database, but it is not easy to use.

There is a catalog routine in the msdn sample, which demonstrates that if you get the table information of a database and the field information in the table, there are two very useful classes in this program: ctables and ccolumns. ctables inherits the crecordset class, encapsulates the sqltables function in a clever way, and stores the result set in the crecordset class for easy retrieval.

In the program, we can apply the following:

// M_db is an opened cdatabse object,

// M_strtableowner is a ccombobox object

Ctables RS (& m_db );

Rs. Open (null, "table ");

Cstring strtableref;

M_combtable.resetcontent ();

While (! Rs. iseof ())

{

Strtableref = _ T ("[");

If (! Rs. m_strtableowner.isempty ())

Strtableref + = Rs. m_strtableowner + _ T ("]. [");

Strtableref + = Rs. m_strtablename + _ T ("]");

M_combtable.addstring (strtableref );

Rs. movenext ();

}

Rs. Close ();

In the ctables object open method, specify the fourth number of energy. "table" indicates the table in the returned database. If this parameter is set to "system table", the system table is returned. If this parameter is set to "system table, returns all tables.

3.2 obtain the field structure in the table.

Three methods are available to structure fields in the table:

① Using the odbc api function sqlcolumn directly, its implementation is also complicated.

② Use the ccolumns class that encapsulates the sqlcolumns function mentioned above. Its usage is similar to that of ctables, and its member variable m_strcolumnname is the field name.

③ Use the member functions of the crecordset class. MFC provides a method to obtain table structure information in the crecordset class, which is very convenient to use. (But it is strange that the cdatabase class does not have a class method to obtain the database structure information ?)

Let's take crecodrset as an example to briefly explain how to get the table structure. Assume that you want to get all the field names of the table selected by the user in the ccombobox object, and export it to the column name of a clistctrl object (whose view attribute is set to report:

// M_strtableowner is the same as the preceding one. It is a ccombobox object.

// M_listdata is the clistctrl object.

Crecordset rs

Codbcfieldinfo Info;

Cstring strsql;

M_combtable.getlbtext (m_combtable.getcursel (), strsql );

Strsql = _ T ("select * from") + strsql;

Rs. Open (open (crecordset: snapshot, strsql, crecordset: readonly );

Int ncolumns = Rs. getodbcfieldcount ();

For (INT nnum = 0; nnum <ncolumns; nnum ++)

{

PRS-> getodbcfieldinfo (nnum, Info );

M_listdata.insertcolumn (nnum, info. m_strname, lvcfmt_left, 80)

}

In addition, we can use the crecordset: getfieldvalue function to obtain the value of the record indicated by the cursor in the record set by specifying the column name or column sequence number. The crecordset: addnew, crecordset :: cancelupdate, crecordset: delete, crecordset: Edit, crecordset: Update, and other function operations.

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.