Клубове Дир.бг
powered by diri.bg
търси в Клубове diri.bg Разширено търсене

Вход
Име
Парола

Клубове
Dir.bg
Взаимопомощ
Горещи теми
Компютри и Интернет
Контакти
Култура и изкуство
Мнения
Наука
Политика, Свят
Спорт
Техника
Градове
Религия и мистика
Фен клубове
Хоби, Развлечения
Общества
Я, архивите са живи
Клубове Дирене Регистрация Кой е тук Въпроси Списък Купувам / Продавам 11:16 24.06.24 
Клубове/ Компютри и Интернет / Бази данни Всички теми Следваща тема Пълен преглед*
Информация за клуба
Тема Re: Visual Basic ili Visual C++???? [re: Reader]
Автор Perin (binary)
Публикувано05.09.02 20:06  



Nai-veroiatno e da izpolzvash ADO za dostap do bazata danni i ot dvata ezika. Koda, koito triabva da napishesh na C za da postignesh sashtia rezultat koito shte postignesh s VB e mnogo poveche. Eto dva primera kopnati ot MSDN koito bi triabvalo da varshat edno i sashto:


'BeginUpdateVB
Public Sub UpdateX()

'To integrate this code
'replace the data source and initial catalog values
'in the connection string

' recordset and connection variables
Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLEmployees As String
' buffer variables
Dim strOldFirst As String
Dim strOldLast As String
Dim strMessage As String

' Open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider=sqloledb;Data Source=MyServer;Initial Catalog=Pubs;User Id=sa;Password=; "
Cnxn.Open strCnxn

' Open recordset to enable changes
Set rstEmployees = New ADODB.Recordset
strSQLEmployees = "SELECT fname, lname FROM Employee ORDER BY lname"
rstEmployees.Open strSQLEmployees, Cnxn, adOpenKeyset, adLockOptimistic, adCmdText

' Store original data
strOldFirst = rstEmployees!fname
strOldLast = rstEmployees!lname
' Change data in edit buffer
rstEmployees!fname = "Linda"
rstEmployees!lname = "Kobara"

' Show contents of buffer and get user input
strMessage = "Edit in progress:" & vbCr & _
" Original data = " & strOldFirst & " " & _
strOldLast & vbCr & " Data in buffer = " & _
rstEmployees!fname & " " & rstEmployees!lname & vbCr & vbCr & _
"Use Update to replace the original data with " & _
"the buffered data in the Recordset?"

If MsgBox(strMessage, vbYesNo) = vbYes Then
rstEmployees.Update
Else
rstEmployees.CancelUpdate
End If

' show the resulting data
MsgBox "Data in recordset = " & rstEmployees!fname & " " & _
rstEmployees!lname

' restore original data because this is a demonstration
If Not (strOldFirst = rstEmployees!fname And _
strOldLast = rstEmployees!lname) Then
rstEmployees!fname = strOldFirst
rstEmployees!lname = strOldLast
rstEmployees.Update
End If

' clean up
rstEmployees.Close
Cnxn.Close
Set rstEmployees = Nothing
Set Cnxn = Nothing

End Sub
' EndUpdateVB



// BeginUpdateCpp
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")

#include <stdio.h>
#include <ole2.h>
#include <malloc.h>
#include <conio.h>
#include "UpdateX.h"

// Function Declartion.
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void UpdateX(void);
void UpdateX2(void);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);

void main()
{
if(FAILED(::CoInitialize(NULL)))
return;

UpdateX();

//Wait here for user to see the output..
printf("\nPress any key to continue...");
getch();

//Clear the screen for the next display
system("cls");

UpdateX2();

::CoUninitialize();
}

//////////////////////////////////////////////////////////
// //
// UpdateX Function //
// //
//////////////////////////////////////////////////////////
void UpdateX(void)
{
HRESULT hr = S_OK;

// Define ADO object pointers.
// Initialize pointers on define.
// These are in the ADODB:: namespace.
_RecordsetPtr pRstEmployees = NULL;

// Define string variables.
_bstr_t strCnn("Provider=sqloledb;Data Source=MyServer;"
"Initial Catalog=pubs;User Id=sa;Password=;");

IADORecordBinding *picRs = NULL; // Interface Pointer declared
CEmployeeRs emprs; // C++ Class object.

try
{
// Open recordset with names from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->CursorType = adOpenKeyset;
pRstEmployees->LockType = adLockOptimistic;
pRstEmployees->Open("SELECT fname, lname FROM Employee "
"ORDER BY lname",strCnn,adOpenKeyset,adLockOptimistic,
adCmdText);

// Store original data.
_bstr_t strOldFirst = pRstEmployees->Fields->
GetItem("fname")->Value;
_bstr_t strOldLast = pRstEmployees->Fields->
GetItem("lname")->Value;

//Change data in edit buffer.
pRstEmployees->Fields->GetItem("fname")->Value =
(_bstr_t)("Linda");
pRstEmployees->Fields->GetItem("lname")->Value =
(_bstr_t)("Kobara");

// Show contents of buffer and get user input.
printf("\n\nEdit in progress:\n\n");

printf("Original data = %s %s \n",
(LPSTR)strOldFirst,(LPSTR)strOldLast);

printf("Data in buffer = %s %s",
(LPSTR)(_bstr_t) pRstEmployees->Fields->
GetItem("fname")->Value,\
(LPSTR) (_bstr_t) pRstEmployees->Fields->
GetItem("lname")->Value);

// Ask if the User wants to Update
printf("\n\nUse Update to replace the original data with the"
" buffered data in the Recordset? (y/n): ");
char chKey = getch();

if(toupper(chKey) == 'Y')
pRstEmployees->Update();
else
pRstEmployees->CancelUpdate();

//Open an IADORecordBinding interface pointer which
//we'll use for binding Recordset to a class.
TESTHR(pRstEmployees->QueryInterface(
__uuidof(IADORecordBinding),(LPVOID*)&picRs));

//Bind the Recordset to a C++ Class here.
TESTHR(picRs->BindToRecordset(&emprs));

pRstEmployees->MoveFirst();

// Show the resulting data.
printf("\nData in recordset = %s %s", emprs.le_fnameStatus ==
adFldOK ? emprs.m_sze_fname : "<NULL>",
emprs.le_lnameStatus == adFldOK ?
emprs.m_sze_lname : "<NULL>");

// Restore original data because this is a demonstration.
if ((strcmp((char *)strOldFirst,emprs.m_sze_fname) &&
strcmp((char *)strOldLast,emprs.m_sze_lname)))
{
pRstEmployees->Fields->GetItem("fname")->Value = strOldFirst;
pRstEmployees->Fields->GetItem("lname")->Value = strOldLast;
pRstEmployees->Update();
}

//Release IADORecordset Interface
if (picRs)
picRs->Release();

// Clean up objects before exit.
pRstEmployees->Close();
}

catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstEmployees->GetActiveConnection();

// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
}

// The next example demonstrates the Update method
// in conjunction with the AddNew method.

//////////////////////////////////////////////////////////
// //
// UpdateX2 Function //
// //
//////////////////////////////////////////////////////////
void UpdateX2(void)
{
HRESULT hr = S_OK;

// Define ADO object pointers.
// Initialize pointers on define.
// These are in the ADODB:: namespace.
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRstEmployees = NULL;

// Define string variables.
_bstr_t strCnn("Provider=sqloledb;Data Source=MyServer;"
"Initial Catalog=pubs;User Id=sa;Password=;");

IADORecordBinding *picRs = NULL; // Interface Pointer declared
CEmployeeRs1 emprs; // C++ Class object.

try
{
// Open a connection.
TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
pConnection->Open(strCnn,"","",NULL);

// Open recordset with data from Employee table.
TESTHR(pRstEmployees.CreateInstance(__uuidof(Recordset)));
pRstEmployees->CursorType = adOpenKeyset;
pRstEmployees->LockType = adLockOptimistic;
pRstEmployees->Open("employee",
_variant_t((IDispatch*)pConnection,true),
adOpenKeyset, adLockOptimistic,adCmdTable);

pRstEmployees->AddNew();
_bstr_t strEmpID = "B-S55555M";
pRstEmployees->Fields->GetItem("emp_id")->Value = strEmpID;
pRstEmployees->Fields->GetItem("fname")->Value =
(_bstr_t) ("Bill");
pRstEmployees->Fields->GetItem("lname")->Value =
(_bstr_t) ("Sornsin");

// Show contents of buffer and get user input.
printf("\n\nAddNew in progress:\n\n");

printf("Data in buffer = %s , %s %s",
(LPSTR) (_bstr_t) pRstEmployees->Fields->
GetItem("emp_id")->Value,
(LPSTR) (_bstr_t) pRstEmployees->Fields->
GetItem("fname")->Value,
(LPSTR) (_bstr_t) pRstEmployees->Fields->
GetItem("lname")->Value);

printf("\n\nUse Update to save buffer to recordset?(y/n):");
char chKey = getch();

if(toupper(chKey) == 'Y')
{
pRstEmployees->Update();

//Open an IADORecordBinding interface pointer which
//we'll use for binding Recordset to a class.
TESTHR(pRstEmployees->QueryInterface(
__uuidof(IADORecordBinding),(LPVOID*)&picRs));

//Bind the Recordset to a C++ Class here
TESTHR(picRs->BindToRecordset(&emprs));

// Go to the new record and show the resulting data.
printf ("\n\nData in recordset = %s , %s %s",
emprs.le_empidStatus == adFldOK ?
emprs.m_sze_empid : "<NULL>",
emprs.le_fnameStatus == adFldOK ?
emprs.m_sze_fname : "<NULL>",
emprs.le_lnameStatus == adFldOK ?
emprs.m_sze_lname : "<NULL>");
}
else
{
pRstEmployees->CancelUpdate();
printf("\n\nNo new record added.\n");
}
// Delete new data because this is a demonstration.
_bstr_t strSQLDelete("DELETE FROM employee WHERE emp_id = '" +
strEmpID + "'");
pConnection->Execute(strSQLDelete ,NULL,adExecuteNoRecords);

//Release IADORecordset Interface
if (picRs)
picRs->Release();

// Clean up objects before exit.
pRstEmployees->Close();
pConnection->Close();
}

catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
}

//////////////////////////////////////////////////////////
// //
// PrintProviderError Function //
// //
//////////////////////////////////////////////////////////
void PrintProviderError(_ConnectionPtr pConnection)
{
// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

if( (pConnection->Errors->Count) > 0)
{
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for(long i = 0; i < nCount; i++)
{
pErr = pConnection->Errors->GetItem(i);
printf("Error number: %x\t%s\n", pErr->Number,
(LPCSTR) pErr->Description);
}
}
}

//////////////////////////////////////////////////////////
// //
// PrintComError Function //
// //
//////////////////////////////////////////////////////////
void PrintComError(_com_error &e)
{

_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print Com errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
// EndUpdateCpp


Alko e samo za bazi dannni kato che li VB e po-lesno. Pishi na C samo ako NE e vazmojno da se svarshi rabotata s VB, primerno triabva ti free-threaded component.

ignorance is bliss


Цялата тема
ТемаАвторПубликувано
* Visual Basic ili Visual C++???? Reader   05.09.02 14:48
. * Re: Visual Basic ili Visual C++???? Perin   05.09.02 20:06
. * VB Xypodilec   11.09.02 13:52
. * Re: VB Perin   11.09.02 18:41
. * Питах, понеже не разбирам от VB! Xypodilec   11.09.02 19:13
. * Re: Питах, понеже не разбирам от VB! Perin   11.09.02 21:18
. * btw, Xypodilec   11.09.02 19:16
. * Re: btw, Perin   11.09.02 21:21
. * Re: btw, Xypodilec   11.09.02 21:42
. * Re: btw, Perin   11.09.02 23:03
. * Re: Visual Basic ili Visual C++???? anton   05.09.02 20:16
. * Re: Visual Basic ili Visual C++???? Reader   09.09.02 16:23
. * zawisi Zod   08.09.02 22:51
. * Re: Visual Basic ili Visual C++???? voyager   09.09.02 10:31
. * Re: Visual Basic ili Visual C++???? Angello   11.09.02 12:57
Клуб :  


Clubs.dir.bg е форум за дискусии. Dir.bg не носи отговорност за съдържанието и достоверността на публикуваните в дискусиите материали.

Никаква част от съдържанието на тази страница не може да бъде репродуцирана, записвана или предавана под каквато и да е форма или по какъвто и да е повод без писменото съгласие на Dir.bg
За Забележки, коментари и предложения ползвайте формата за Обратна връзка | Мобилна версия | Потребителско споразумение
© 2006-2024 Dir.bg Всички права запазени.