Click here to Skip to main content
15,907,281 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
steps and code to connect to SQL server 2008 for inserting, updating, accessing database using vc++ mfc
Posted

1 solution

Hi!
You should use CDatabase[^] and CRecordset[^] classes to work with databases in MFC.
If you plan to work with varbinary() datatypes the following tech note could be useful:
TN045: MFC/Database Support for Long Varchar/Varbinary[^]
 
Share this answer
 
Comments
BJayashree 15-May-13 3:16am    
i need the complete code
BJayashree 15-May-13 3:17am    
thanks for the answer as im a beginner i need the complete code
Jochen Arndt 15-May-13 3:29am    
You would not get complete code here. The web is full of examples on using the MFC CDatabase and CRecordset classes. These classes are database format independant. The only database format specific tasks are connecting to the database and when using database specific SQL commands.

If you have a specific problem with these classes, we will be pleased to help you.
skydger 15-May-13 4:30am    
As Jochen Arndt wrote you won't get a complete code here. Your request covers a wide field of solutions and we cannot guess which one of them you ment. Please refer this link, maybe this tutorial will be useful:
http://www.informit.com/library/content.aspx?b=Visual_C_PlusPlus&seqNum=190
BJayashree 15-May-13 4:15am    
CDatabase database;
CString SqlString;
CString ssn,firstname;
CString sDriver = _T("SQL Server");
CString sDsn, sMc;
sMc.Format(_T("MERILDSK33"));
CString sFile = _T("C:\\Program Files\\Microsoft SQL Server\\MSSQL10.MSSQLSERVER\\MSSQL\\DATA\\DBTrial.mdf");
sDsn.Format(_T("ODBC;DRIVER={%s};Server=%s;Database=%s;Trusted_Connection=yes"),sDriver,sMc,sFile);

// You must change above path if it's different
int iRec = 0;
try
{
// Open the database
database.Open(NULL,false,false,sDsn);
// Allocate the recordset
CRecordset recset(&database);
// Build the SQL statement
SqlString = _T("select * from dbo.Person");
// Execute the query
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
// Reset List control if there is any data
while( !recset.IsEOF() )
{
recset.GetFieldValue(_T("SSN"),ssn);
recset.GetFieldValue(_T("PersonFN"),firstname);
recset.MoveNext();
}
database.Close();
}
catch(CDBException* e)
{
AfxMessageBox(e->m_strError);
}
I have written above code for connection ,but it fails at database.open line

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900