Q | access数据库SQL问题 |
T | 有两个access的MDB文件(f1.mdb f2.mdb),每个文件里都有一个表为ta,ta有两个字段为"名称","数量",现在要合并这两个MDB文件的数据到第三个文件(f3.mdb该文件已经有一个空的表ta),第三个文件数据结构和这两个MDB文件一致。合并时如果名称相同则数量相加,我不想一条记录一条记录的处理。我在网上看到在access不同数据库中的表进行链接(in)介绍,我想用链接(in)类似下面代码解决问题 insert into ta(名称,数量) select * from 文件f1的ta,in 文件f2的ta group by 名称 请问这个SQL怎么写? |
A | select [name],sum([count]) as sumofcount from query1 group by name |
Q | 想用access做个学生成绩统计的数据库,请问如何实现自动生成名次? |
T | 谢了 |
A | 用一个查询就可以 比如按成绩顺序的话,你统计一下成绩比当前成绩多的学生数目就可以了 一点都不难 select rank=count(*), a1.studentname, a1.score from student a1, student a2 where a1.score >= a2.score group by a1.studentname, a1.score order by a1.score SELECT a1.studentid, a1.studentname, a1.score, Sum(a2.studentid) AS rank FROM student AS a1, student AS a2 WHERE (((a1.score)>=[a2].[score])) GROUP BY a1.studentid, a1.studentname, a1.score ORDER BY a1.studentname, a1.score; |
Q | 高手请指教!! |
T | 以下是我有DAO技术访问ACCESS中的二进制信息: m_pRecordset->Move(81304); COleVariant BinaryValue; m_pRecordset->GetFieldValue("Index",BinaryValue);//"Index"是OLE型的 UINT MyInt1[10]; memcpy(MyInt1,BinaryValue.puintVal,40); ///////////////////////////////////////// 为什么取不出二进制信息呢? |
A | value的类型应该是VT_ARRAY吧……不能当int*使用的…… Visual C++ Concepts: Adding Functionality DAO Record Field Exchange (DFX) DFX_BinarySee Also MFC Macros and Globals | DFX_Text | DFX_Bool | DFX_Currency | DFX_Long | DFX_Short | DFX_Single | DFX_Double | DFX_DateTime | DFX_Byte | DFX_LongBinary | CDaoFieldExchange::SetFieldType Transfers arrays of bytes between the field data members of a CDaoRecordset object and the columns of a record on the data source. void AFXAPI DFX_Binary( CDaoFieldExchange* pFX, LPCTSTR szName, CByteArray& value, int nPreAllocSize = AFX_DAO_BINARY_DEFAULT_SIZE, DWORD dwBindOptions = 0 ); |
Q | 请问:WIN98下怎样注册MSADO15.DLL这个组件? 用regsvr32.exe msado15.dll它说loadlibrary fail |
T | MSADO15.DLL是从WIN XP HOME版拷过来的。我的程序在XP下运行正常,能使用access数据库。 把程序拷到WIN 98下,运行时非法操作,指向ADO的执行语句。在WIN98的系统目录下想注册MSADO15.DLL。命令行如下: c:/pwin98/system/regsvr32.exe msado15.dll 报错:LoadLibrary("msado15.dll") fail! 我应该怎样注册这个ADO COM组件?? 谢谢! |
A | MSDN MDAC SDK Technical Articles Redistributing Microsoft Data Access Components ADO 2.7 Programmer's Guide Installing and Redistributing ADO MDAC components consist of a matched set of dynamic-link libraries (DLLs). It is not enough to simply install Msado15.dll, for example, for ADO to work correctly. You need the complete set of ADO DLLs, as well as an underlying OLE DB provider (which usually has one DLL plus a set of helper DLLs) and ODBC. You can download the latest version of MDAC_TYP.exe from the following Microsoft Web site: http://www.microsoft.com/data/download.htm The MDAC_TYP.exe setup includes only the binaries necessary to redistribute the components; it doesn't include documentation. Note that in addition to MDAC_TYP.exe, you may need to distribute DCOM95 for your Windows 95 clients. DCOM must be installed prior to the installation of MDAC. Note that Windows 2000, Windows NT 4.0, and Windows 98 have DCOM built in. You can download the latest version of DCOM95 from the following Microsoft Web site: http://www.microsoft.com/com Note that DCOM must be installed separately and before MDAC_TYP.exe and your Setup program. DCOM cannot be installed from within your Setup program. |
Q | 吐血!如何从数据库中得到1970年以前的时间? |
T | 用CRecordset类得到数据库中的时间的时候,发现对于1970年以前的时间,无论如何返回的都是1970-1-1,查MSDN才知道CRecordset交换时间用的是RFX_DATE,而这个返回的时间类型是CTime类型的,CTime类型的时间又限制在1970-2038,当时就快吐血了,各位老兄帮忙,分不够可以再加,只要解决这个问题啊。 |
A | void AFXAPI DFX_DateTime( CDaoFieldExchange* pFX, LPCTSTR szName, COleDateTime& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE ); |
Q | 如何创建ACCESS2000数据库.mdb文件 |
T | 用ADO能否实现? |
A | 可以。也可以用SQLConfigDataSource创建。 Use of SQLConfigDataSource ODBC installer DLL API function: BOOL fCreated; fCreated = SQLConfigDataSource(NULL, ODBC_ADD_DSN, "Microsoft Access Driver (*.mdb)", "CREATE_DB=.//ATest.mdb General/0" ); This will create ATest.mdb in the application's working directory using general sorting. BOOL SQLConfigDataSource(hwndParent, fRequest, lpszDriver, lpszAttributes) Where: hwndParent is either NULL if no dialogs are to be displayed or a valid hwnd to act as parent to any driver generated dialogs. fRequest is ODBC_ADD_DSN to specify creation of the .mdb file. lpszDriver is Microsoft Access Driver (*.mdb). lpszAttributes is "CREATE_DB=<path><filename>.mdb <sort order>/0" where the <path><filename> combination identifies where the file should be created and <sort order> is language sorting order (for example, General). <path> must be specified even if the .mdb is to be created in the current working directory. Use standard relative path syntax. NOTE: Unlike most other ODBC API functions, SQLConfigDataSource returns a boolean value. This return value is TRUE if the .mdb was created, FALSE if creation failed. |
Q | 如何用ADO中的_RecordsetPtr对象做参数(变量)查询? |
T | 比如说: _RecordsetPtr m_pRecordset; m_pRecordset->("select * from 表名 where 字段名=一个变量",...)这句话改如何写?谢谢 |
A | #import "C:/Program Files/Common Files/System/ado/msado15.dll" / rename( "EOF", "adoEOF" ) ... _variant_t vtEmpty (DISP_E_PARAMNOTFOUND, VT_ERROR); _variant_t vtEmpty2(DISP_E_PARAMNOTFOUND, VT_ERROR); ... ADODB::_ConnectionPtr Conn1; ADODB::_CommandPtr Cmd1; ADODB::_ParameterPtr Param1; ADODB::_RecordsetPtr Rs1; // Trap any error/exception. try { // Create and Open Connection Object. Conn1.CreateInstance( __uuidof( ADODB::Connection ) ); Conn1->ConnectionString = _bstr_t(L"DSN=Biblio;UID=adimin;PWD=;"); Conn1->Open( _bstr_t(L""), _bstr_t(L""), _bstr_t(L""), -1 ); // Create Command Object. Cmd1.CreateInstance( __uuidof( ADODB::Command ) ); Cmd1->ActiveConnection = Conn1; Cmd1->CommandText = _bstr_t(L"SELECT * FROM Authors " L"WHERE Au_ID < ?"); // Create Parameter Object. Param1 = Cmd1->CreateParameter( _bstr_t(L""), ADODB::adInteger, ADODB::adParamInput, -1, _variant_t( (long) 5) ); Param1->Value = _variant_t( (long) 5 ); Cmd1->Parameters->Append( Param1 ); // Open Recordset Object. Rs1 = Cmd1->Execute( &vtEmpty, &vtEmpty2, ADODB::adCmdText ); } catch( CException *e ) { e->Delete(); } catch(...) { } For a demonstration of how to use a Parameterized Query either with classes generated by the Microsoft Foundation Class (MFC) ClassWizard, or using straight COM programming, please see the ADOVC sample referenced in the REFERENCES section. |
Q | 不行了,快被折磨死了,谁能救救我,一个关于VC访问数据库的问题。 |
T | 我用CDatabase类通过ODBC连接SQL Server数据库,执行SQL语句如下: select count(id) as num from info_check_t_gatewaydata where sendtime>='2001-08-11 16:32:32' and sendtime<='2001-08-14 16:32:32' 该语句在SQL Server的分析器中运行没有任何问题。可在VC中运行却报错,错误内容如下: The conversion of a char data type to a datetime data type resulted in an out_of_range datetime type. 不知道怎样转换类型才能运行。我用CRecordset类的OPEN函数调用该SQL语句: clsRecordset.Open(AFX_DB_USE_DEFAULT_TYPE,strSql,0);这应该没什么问题吧!可就是总报错,希望哪位老兄能帮我一把。一定给分。 |
A | CString g_FmtDBDateTime(COleDateTime tTime, BOOL bDate/*=TRUE*/, BOOL bTime/*=TRUE*/) { if(tTime.GetStatus()!=COleDateTime::valid) return "null"; CString strFormat; strFormat="#"; if(bDate) strFormat+="%m/%d/%Y"; if(bDate&&bTime) strFormat+=" "; if(bTime) strFormat+="%H:%M:%S"; strFormat+="#"; return tTime.Format(strFormat); } 在Access里面都是用#的呀? 和到SQL的连接的设置有关。Select一下看看时间是怎么显示的 以前自己存数据的时候,用字符串年年月月日日时时分分秒秒表示时间,比较字符串就可以判断时间 |
Q | 谁能给我用ADO读写access的范例? |
T | 我这次问的是ADO,不是DAO :) 初学数据库,还请多指教! |
A | 哦 #include <windows.h> #import <msado15.dll> rename("EOF", "adoEOF") ... Init Ole ... void main() { HRESULT hr = S_OK; ADODB::_RecordsetPtr Rs1 = NULL; _bstr_t Connect( "DSN=AdoDemo;UID=admin;PWD=;" ); _bstr_t Source ( "SELECT * FROM Authors" ); hr = Rs1.CreateInstance( __uuidof( ADODB::Recordset ) ); Rs1->Open( Source, Connect, ADODB::adOpenForwardOnly, ADODB::adLockReadOnly, -1 ); Rs1->Close(); Rs1 = NULL; ::MessageBox( NULL, "Success!", "", MB_OK ); } AfxOleInit(); ... _Recordset Rs1; COleException e; COleVariant Connect( "DSN=AdoDemo;UID=admin;PWD=;" ); COleVariant Source ( "SELECT * FROM Authors" ); Rs1.CreateDispatch( "ADODB.Recordset.2.0", &e ); Rs1.Open( (VARIANT) Source, (VARIANT) Connect, 0, 1, -1 ); Rs1.Close(); Rs1.ReleaseDispatch(); AfxMessageBox("Success!"); #include <windows.h> #include <initguid.h> // Include only once in your application #include "adoid.h" // ADO GUID's #include "adoint.h" // ADO Classes, enums, etc. ... INIT OLE ... void main() { HRESULT hr = S_OK; ADORecordset* Rs1 = NULL; VARIANT Source; VARIANT Connect; VariantInit( &Source ); VariantInit( &Connect ); Source.vt = VT_BSTR; Source.bstrVal = ::SysAllocString( L"SELECT * FROM Authors"); Connect.vt = VT_BSTR; Connect.bstrVal = ::SysAllocString( L"DSN=AdoDemo;UID=admin;PWD=;" ); hr = CoCreateInstance( CLSID_CADORecordset, NULL, CLSCTX_INPROC_SERVER, IID_IADORecordset, (LPVOID *) &Rs1 ); if( SUCCEEDED( hr ) ) hr = Rs1->Open( Source, Connect, adOpenForwardOnly, adLockReadOnly, -1 ); if( SUCCEEDED( hr ) ) hr = Rs1->Close(); if( SUCCEEDED( hr ) ) { Rs1->Release(); Rs1 = NULL; } if( SUCCEEDED( hr ) ) ::MessageBox( NULL, "Success!", "", MB_OK ); MSDN2001Jan/Platform SDK/Data Services/Microsodr ActiveX Data Objects(ADO) sWord = (LPCTSTR)V_BSTR(&vWord); or sWord = (LPCTSTR)vWord.bstrVal; |
Q | 在web上怎样实现与access数据库连接(vc) |
T | 在web上怎样实现与access数据库连接(vc) |
A | ISAPI+ADO? …… 这里就是讨论这个的 http://www.blogcn.com/user3/jiangsheng/main.asp?id=638551 |
Q | 菜鸟又来了:用VC++编程,怎样联接到SQL服务器上,并操作它里面的数据库? |
T | 1、用VC++编程,怎样联接到SQL服务器上,并操作它里面的数据库? 2、直接用ODBC联连本地数据库与联连到SQL上,通过它再来访问数据库,在性能上有很大差别吗? |
A | 1建立一个数据源 2建立RDO对象 3通过连接字符串访问。 出处:www.csdn.net 连接数据库查询手册(不仅仅适用于asp)(ghj1976 转贴) 出处:http://www.active.com.cn 正文: 下面将简单介绍一下几种ADO连接方式:ODBC DSN,ODBC DSN-Less, OLE DB Provider,和"MS Remote" Provider. 1。ODBC DSN连接 I.DSN oConn.Open "DSN=AdvWorks;" & _ "UID=Admin;" & _ "PWD=;" 注意:从MDAC2.1开始就不能够在使用这样的方式了,就是只把DSN文件名放在ConnectString中 你必须同时使用DSN,UID,PWD标志。例如下面的方式在MDAC 2.1中将会出错: oConn.Open "AdvWorks" II.File DSN oConn.Open "FILEDSN=/somepath/mydb.dsn;" & _ "UID=Admin;" & _ "PWD=;" III.ODBC DSN-Less Connections a)ODBC Text Driver oConn.Open _ "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _ "Dbq=/somepath/;" & _ "Extensions=asc,csv,tab,txt;" & _ "Persist Security Info=False" 注意:需要在SQL语句中指定使用到的文件名。例如: oRs.Open "Select * From customer.csv", _ oConn, adOpenStatic, adLockReadOnly, adCmdText b)ODBC Driver for Access i)普通安全模式: oConn.Open _ "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=/somepath/mydb.mdb;" & _ "Uid=Admin;" & _ "Pwd=;" ii)如果使用了System database: oConn.Open _ "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=/somepath/mydb.mdb;" & _ "SystemDB=/somepath/mydb.mdw;", _ "admin", "" c)ODBC Driver for SQL Server i)普通安全模式 oConn.Open "Driver={SQL Server};" & _ "Server=carl2;" & _ "Database=pubs;" & _ "Uid=sa;" & _ "Pwd=;" ii)使用信任安全模式: oConn.Open "Driver={SQL Server};" & _ "Server=carl2;" & _ "Database=pubs;" & _ "Uid=;" & _ "Pwd=;" 注意:要使用空白的Uid和Pwd d)ODBC Driver for Oracle i)使用现有的Oracle ODBC Driver from Microsoft: oConn.Open _ "Driver={Microsoft ODBC for Oracle};" & _ "Server=OracleServer.world;" & _ "Uid=demo;" & _ "Pwd=demo;" ii)使用老版本的Oracle ODBC Driver from Microsoft: oConn.Open _ "Driver={Microsoft ODBC Driver for Oracle};" & _ "ConnectString=OracleServer.world;" & _ "Uid=demo;" & _ "Pwd=demo;" IIII)使用微软的OLE DB Data Link Connections方式Data Link File (UDL) a)使用绝对路径 oConn.Open "File Name=/somepath/pubs.udl;" b)使用相对路径 oConn.Open "File Name=pubs.udl;" V)OLE DB Provider Connections方式 a)OLE DB Provider for ODBC Databases i)Access (Jet): oConn.Open _ "Provider=MSDASQL;" & _ "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=/somepath/mydb.mdb;" & _ "Uid=Admin;" & _ "Pwd=;" ii)SQL Server: oConn.Open _ "Provider=MSDASQL;" & _ "Driver={SQL Server};" & _ "Server=carl2;" & _ "Database=pubs;" & _ "Uid=sa;" & _ "Pwd=;" b)OLE DB Provider for Microsoft Jet (Access) i)普通安全模式: oConn.Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=/somepath/mydb.mdb;" & _ "User Id=admin;" & _ "Password=;" ii)如果使用了System database: oConn.Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=/somepath/mydb.mdb;" & _ "Jet OLEDB:System Database=system.mdw;", _ "admin", "" 注意:当使用OLE DB Provider4.0版本是,需要把MDB和MDW文件转换成4.0的数据库格式 iii)如果MDB需要一个数据库密码的话: oConn.Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=/somepath/mydb.mdb;" & _ "Jet OLEDB:Database Password=MyDbPassword;", _ "admin", "" c)OLE DB Provider for Excel Spreadsheet: oConn.Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=/somepath/expenses.xls;" & _ "Extended Properties=""Excel 8.0;HDR=Yes;"";" 注意: "HDR=Yes"表示在第一行中是行标题,在provider中将不把第一行包括入recordset中 d)OLE DB Provider for SQL Server i)普通安全模式: oConn.Open "Provider=sqloledb;" & _ "Network Library=DBMSSOCN;" & _ "Data Source=carl2;" & _ "Initial Catalog=pubs;" & _ "User Id=sa;" & _ "Password=;" ii)使用信任安全模式: oConn.Open "Provider=sqloledb;" & _ Network Library=DBMSSOCN;" & _ "Data Source=carl2;" & _ "Initial Catalog=pubs;" & _ "Trusted_Connection=yes;" 注意:"Network Library=DBMSSOCN"声明OLE DB使用TCP/IP替代Named Pipes. e)OLE DB Provider for Oracle oConn.Open "Provider=msdaora;" & _ "Data Source=OracleServer.world;" & _ "User Id=sa;" & _ "Password=;" (VI)Remote OLE DB Provider Connections方式(就是我一直在研究的RDS方式哦,呵呵。): a)MS Remote - Access (Jet) i)ODBC DSN: oConn.Open "Remote Server=http://carl2;" & _ "Remote Provider=MSDASQL;" & _ "DSN=AdvWorks;" & _ "Uid=admin" & _ "Pwd=;" ii)OLE DB Provider: oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://carl2;" & _ "Remote Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=/somepath/mydb.mdb;", _ "admin", "" iii)OLE DB Provider自定义事务对象 oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://carl2;" & _ "Handler=MSDFMAP.Handler;" & _ "Data Source=MyAdvworksOLEDBConnectTag;" b)MS Remote - SQL Server i)ODBC DSN: oConn.Open "Remote Server=http://carl2;" & _ "Remote Provider=MSDASQL;" & _ "Network Library=DBMSSOCN;" & _ "DSN=Pubs;" & _ "Uid=sa" & _ "Pwd=;" ii)OLE DB Provider oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://carl2;" & _ "Remote Provider=SQLOLEDB;" & _ "Network Library=DBMSSOCN;" & _ "Data Source=carl2;" & _ "Initial Catalog=pubs;" & _ "User ID=sa;" & _ "Password=;" |
Q | 急!关于DBCombo控件? |
T | DBCombo控件的SetRowSource(LPDISPATCH newValue)中的LPDISPATCH newValue 怎么得到??? |
A | BOOL CMyDlg::OnInitDialog() { // Find the child controls on the dialog CWnd* pDSC = GetDlgItem(IDC_REMOTEDATACONTROL); CDBListBox* pList = (CDBListBox*) GetDlgItem(IDC_DBLISTBOX); // Tell the MFC binding manager that we are // binding DISPID 3 to the data-source control. pList->BindProperty(0x3, pDSC); // Tell the listbox which field to expose as its // bound column pList->SetBoundColumn(_T("CourseID")); // Tell the listbox which cursor and column // to populate its list from pList->SetListField(_T("CourseID")); IPUNKNOWN *pcursor = pDSC->GetDSCCursor(); ... if (!pcursor) { // The pointer was not successfully assigned. return FALSE; } // The pointer was successfully assigned, pList->SetRowSource(pcursor); ... pcursor->Release(); return TRUE; } MDIBIND: Databound Controls in CWnd-Derived Windows Click to open or copy the MDIBIND project files. The MDIBIND sample demonstrates that data binding can be done with any CWnd-derived windows, but only at run time. An AppWizard-generated MDI application is used for this sample. Data source and databound controls are created in CView-derived window client areas. MDIBIND supports three document templates: RDC – its view displays a Data Source control Grid - its view displays a Grid control Edit - its view displays a masked edit control (see note below about using Masked Edit controls in Visual C++) Running the Sample You can open/create the child windows based on these templates. With the Bind command from the Window menu, you can bind each control. For the Grid control and Edit control, choose the data source from any available RDC window and specify the column if required. If the currently selected data source control is active, its results set is used to fill the Column Name box with appropriate column names. For the Data Source control, you can specify the ODBC data source, user name, password, and SQL statement (just as you can specify these parameters in the resource editor at design time). Note that all bound controls change appropriately when you change the underlying data source name (DSN) by selecting another data source. Note The Masked Edit control does not automatically format its contents. When the Masked Edit Controls Format property is set, it does not automatically format its contents upon losing focus. When embedded in a Visual Basic or Access form, the control automatically formats its contents when the control loses focus. The Masked Edit Control uses a proprietary Visual Basic interface called IVBFormat. Control container applications written with Visual C++ do not support this interface. The absence of IVBFormat support in a control container prevents the Masked Edit Control from automatically updating its contents as specified by the Format property. The Masked Edit Control can still be used in a Visual C++ control container application. However, the automatic formatting feature will be disabled. Other properties, like the Mask property and databinding properties function properly in the absence of the IVBFormat support. This sample demonstrates the following keywords: CWnd::Create; CWnd::BindProperty; CWnd::BindDefaultProperty;CWnd::GetDSCCursor |
Q | How to register mdb to ODBC? |
T | I use CDaoDatebase Create a mdb database, I want to register it to ODBC, How to do it? of course, in programe. |
A | void Build_SystemDSN(CString DSN_NAME ,CString Db_Path ) { int ret; CString Driver, Attributes; Driver = "Microsoft Access Driver (*.MDB)"; Attributes = "DSN=" + DSN_NAME +"Uid=Admin"+"pwd=" +"DBQ=" + Db_Path ; ret = SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, Driver, Attributes); //ret is equal to 1 on success and 0 if there is an error If(ret!=1) AfxMessageBox( "DSN Creation Failed"); } |
Q | 不借助CRecordSet,怎么访问数据库? |
T | 我现在编写的一个程序是Win32 Application的,无法用CRecordSet类,如何访问数据库? |
A | Open and Close Methods Example (VC++) This example uses the Open and Close methods on both Recordset and Connection objects that have been opened. // BeginOpenCpp #import "C:/Program Files/Common Files/System/ADO/msado15.dll" no_namespace rename("EOF", "EndOfFile") #include <oledb.h> #include <stdio.h> #include <conio.h> #include "OpenX.h" // Function declarations inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);}; void OpenX(void); void PrintProviderError(_ConnectionPtr pConnection); void PrintComError(_com_error &e); /////////////////////////////////////////////////////////// // // // Main Function // // // /////////////////////////////////////////////////////////// void main() { if(FAILED(::CoInitialize(NULL))) return; OpenX(); ::CoUninitialize(); } /////////////////////////////////////////////////////////// // // // OpenX Function // // // /////////////////////////////////////////////////////////// void OpenX(void) { // Define ADO object pointers. // Initialize pointers on define. // These are in the ADODB:: namespace _RecordsetPtr pRstEmployee = NULL; _ConnectionPtr pConnection = NULL; // Define string variables. _bstr_t strCnn("Provider=sqloledb;Data Source=MyServer;" "Initial Catalog=pubs;User Id=sa;Password=;"); // Define Other Variables. HRESULT hr = S_OK; IADORecordBinding *picRs = NULL; // Interface Pointer declared. CEmployeeRs emprs; // C++ Class object DBDATE varDate; try { // open connection and record set TESTHR(pConnection.CreateInstance(__uuidof(Connection))); pConnection->Open(strCnn,"","",adConnectUnspecified); TESTHR(pRstEmployee.CreateInstance(__uuidof(Recordset))); pRstEmployee->Open("Employee", _variant_t((IDispatch *)pConnection,true), adOpenKeyset, adLockOptimistic, adCmdTable); // Open an IADORecordBinding interface pointer which we'll // use for Binding Recordset to a class. TESTHR(pRstEmployee->QueryInterface( __uuidof(IADORecordBinding),(LPVOID*)&picRs)); //Bind the Recordset to a C++ Class here. TESTHR(picRs->BindToRecordset(&emprs)); // Assign the first employee record's hire date // to a variable, then change the hire date. varDate = emprs.m_sze_hiredate; printf("/nOriginal data/n"); printf("/tName - Hire Date/n"); printf(" %s %s - %d/%d/%d/n/n", emprs.le_fnameStatus == adFldOK ? emprs.m_sze_fname : "<NULL>", emprs.le_lnameStatus == adFldOK ? emprs.m_sze_lname : "<NULL>", emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.month : 0, emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.day : 0, emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.year : 0); emprs.m_sze_hiredate.year=1900; emprs.m_sze_hiredate.month=1; emprs.m_sze_hiredate.day=1; picRs->Update(&emprs); printf("/nChanged data/n"); printf("/tName - Hire Date/n"); printf(" %s %s - %d/%d/%d/n/n", emprs.le_fnameStatus == adFldOK ? emprs.m_sze_fname : "<NULL>", emprs.le_lnameStatus == adFldOK ? emprs.m_sze_lname : "<NULL>", emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.month : 0, emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.day : 0, emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.year : 0); // Requery Recordset and reset the hire date. pRstEmployee->Requery(adOptionUnspecified); // Open an IADORecordBinding interface pointer which we'll // use for Binding Recordset to a class. TESTHR(pRstEmployee->QueryInterface( __uuidof(IADORecordBinding),(LPVOID*)&picRs)); // Rebind the Recordset to a C++ Class here. TESTHR(picRs->BindToRecordset(&emprs)); emprs.m_sze_hiredate = varDate; picRs->Update(&emprs); printf("/nData after reset/n"); printf("/tName - Hire Date/n"); printf(" %s %s - %d/%d/%d",emprs.le_fnameStatus == adFldOK ? emprs.m_sze_fname : "<NULL>", emprs.le_lnameStatus == adFldOK ? emprs.m_sze_lname : "<NULL>", emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.month : 0, emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.day : 0, emprs.le_hiredateStatus == adFldOK ? emprs.m_sze_hiredate.year : 0); // Clean up objects before exit. pRstEmployee->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("/t Error number: %x/t%s", pErr->Number, 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); } // EndOpenCpp OpenX.h: // BeginOpenH #include "icrsint.h" // This Class extracts only fname,lastname and // hire_date from employee table class CEmployeeRs : public CADORecordBinding { BEGIN_ADO_BINDING(CEmployeeRs) // Column fname is the 2nd field in the table ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_sze_fname, sizeof(m_sze_fname), le_fnameStatus, FALSE) // Column lname is the 4th field in the table. ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_sze_lname, sizeof(m_sze_lname), le_lnameStatus, FALSE) // Column hiredate is the 8th field in the table. ADO_VARIABLE_LENGTH_ENTRY2(8, adDBDate,m_sze_hiredate, sizeof(m_sze_hiredate), le_hiredateStatus, TRUE) END_ADO_BINDING() public: CHAR m_sze_fname[21]; ULONG le_fnameStatus; CHAR m_sze_lname[31]; ULONG le_lnameStatus; DBDATE m_sze_hiredate; ULONG le_hiredateStatus; }; // EndOpenH |
Q | 如何为msdatagrid控件动态绑定数据源? |
T | |
A | http://download.microsoft.com/download/vc60pro/Utility/1.0/W9X/EN-US/Mfceqado.exe SAMPLE: Mfceqado.exe Shows How to Use English Query with MFC and ADO ID: Q229612 -------------------------------------------------------------------------------- The information in this article applies to: Microsoft Visual C++, 32-bit Editions, version 6.0 Microsoft English Query, version 7.0 ActiveX Data Objects (ADO), versions 2.1, 2.5 -------------------------------------------------------------------------------- SUMMARY Mfceqado.exe is an English Query ADO Visual C++ sample that uses ADO in a Visual C++ MFC application to query SQL Server statements generated by the English Query engine. The sample uses DataGrid Control version 6.0 (OLEDB) to display the results. The English Query code used in this sample is very similar to the MFCUI C++ Remote Data Objects (RDO) English Query sample that ships with the SQL Server 7.0 CD-ROM. Refer to the following Microsoft Knowledge Base article for more information on how to use DataGrid Control with ADO in Visual C++: Q229029 SAMPLE: AdoDataGrid.exe Demonstrates Using ADO with DataGrid Steps to Run Sample Build and run Mfcequi.exe. Specify an English Query (EQ) application (.eqc) file and a question (.eqq) file in the Welcome dialog box. You can use either the Pubs.eqc or NorthWind.eqc sample EQ files that are installed by EQ in the samples folder. Click Start Application in the Welcome dialog box. Choose a SQL Server 7.0 data source in the ODBC Administrator dialog box that displays when you click Start Application. Enter an English sentence to query into the main query dialog box. For example, enter the following query for the pubs database if you select Pubs.eqc in step 2: How many authors live in Oakland ? Click Submit to run the query. The English Query parses the English statment to generate SQL language. The application uses ADO to submit the SQL statement to SQL Server. The DataGrid displays the results. Click Show SQL to see SQL language command sent to SQL Server. |
Q | 用VC操作Access数据库来新增(addnew())一条记录时,我需要为(自动编号)类型的字段(主键)赋值(SetFieldValue())吗? |
T | 怎样自增自动编号的字段值呢? |
A | Sample Code // Open database. CDaoDatabase db; db.Open(_T("c://db1.mdb")); // Create a table called MySeekTable with a GUID primary key field named // ID and a field named Found. db.Execute(_T("create table MySeekTable (ID guid constraint PKEY primary key, Found text)")); // Insert a few records using an insert into statement. db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {11111111-aabb-aabb-aabb-aabbccddeeff}},'Guid1')")); db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {22222222-aabb-aabb-aabb-aabbccddeeff}},'Guid2')")); db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {33333333-aabb-aabb-aabb-aabbccddeeff}},'Guid3')")); // Open table-type recordset (must use table-type for Seek) and select // index for seek. CDaoRecordset rs(&db); rs.Open(dbOpenTable,_T("MySeekTable")); rs.SetCurrentIndex(_T("PKEY")); // Construct the GUID you want to find and seek the GUID. COleVariant varGUIDValue(_T("{guid {22222222-aabb-aabb-aabb- aabbccddeeff}}"), VT_BSTRT); if (rs.Seek(_T("="),&varGUIDValue)) { // GUID found. Retrieve and display value. CString strResult = V_BSTRT(&rs.GetFieldValue(_T("Found"))); AfxMessageBox("Seek of guid found '" + strResult + "'"); } else { // GUID not found. AfxMessageBox("Seek of guid failed."); } |
Q | Access是否支持事务处理??? |
T | Access是否支持事务处理,如果不能那VC++中有关事务处理的函数就不能用了??? |
A | 当然支持 CDaoWorkspace::CommitTrans void CommitTrans( ); throw( CDaoException, CMemoryException ); Remarks Call this member function to commit a transaction — save a group of edits and updates to one or more databases in the workspace. A transaction consists of a series of changes to the database’s data or its structure, beginning with a call to BeginTrans. When you complete the transaction, either commit it or roll it back (cancel the changes) with Rollback. By default, without transactions, updates to records are committed immediately. Calling BeginTrans causes commitment of updates to be delayed until you call CommitTrans. |
Q | 有关access数据库的问题 |
T | 有两个access的MDB文件,每个文件里都有一个表为ta,ta有两个字段为"名称","数量",现在要合并这两个MDB文件的数据形成第三个文件,第三个文件数据结构和这两个MDB文件一致。合并时如果名称相同则数量相加,直接插入。现在采用的方案是在第三个文件中建立两个链接表,分别指向第一/二个文件中的ta表。然后采用insert into ...select..from...的方式,但是这种方式依赖于那两个链接表(目前必须手动建立),有没有高手知道建立链接表的代码?或者其他可以脱离手动操作成批插入数据的方法? |
A | CDaoTableDef::Create virtual void Create( LPCTSTR lpszName, long lAttributes = 0, LPCTSTR lpszSrcTable = NULL, LPCTSTR lpszConnect = NULL ); throw( CDaoException, CMemoryException ); Parameters ..... lAttributes A value corresponding to characteristics of the table represented by the tabledef object. You can use the bitwise-OR to combine any of the following constants: Constant Description dbAttachExclusive For databases that use the Microsoft Jet database engine, indicates the table is an attached table opened for exclusive use. dbAttachSavePWD For databases that use the Microsoft Jet database engine, indicates that the user ID and password for the attached table are saved with the connection information. lpszSrcTable A pointer to a string containing the source table name. By default this value is initialized as NULL. lpszConnect A pointer to a string containing the default connect string. By default this value is initialized as NULL. sample code Create("First Quarter Sales",0,"Q1Sales", "Paradox 4.x;DATABASE=//Sales/Regional/Region1;PWD=RollsRoyce;"); Create("Western Region Sales", 0, "Q1Sales","FoxPro 3.0;DATABASE=//Sales/Regional/Region1;"); Create("Authors", 0, "authors",";DATABASE=./Pubs.mdb;pwd=password;" ); |
Q | ado编程问题讨论:如何在插入一条纪录后立刻得到该条纪录的编号?(编号是自动递增的主键) |
T | 我开始用这种方法: m_Recordset->AddNew(); m_Recordset->PutCollect() m_Recordset->Update(); long id; id=m_Recordset->Fields->GetItem(_variant_t(short(0)))->Value; 但得到的id号永远是0。 后来在update()后加上一句m_Recordset->MoveLast();就可以了。我有点不甘心,如果我的表很大,这样做企不是有点浪费?而且如果插入速度很快的话(同时有很多插入),movelast后得到的id有没有可能会出错? 欢迎指教。 |
A | HOWTO: Return Record's Autonumber Value Inserted into Access DB Q221931 SUMMARY When a new record is added to an ActiveX Data Objects (ADO) Recordset that contains an Autonumber field, immediately reporting the value of the Autonumber field for the inserted record returns a value of 0. This article describes how to retrieve the automatically generated value of an Autonumber field of a record inserted into an Access database with the ADO AddNew() and Update() methods. Following are some key elements to note: The CursorLocation must be adUseClient. Access does not support a server-side cursor. In order to populate the Autonumber field with the automatically generated value, the recordset must be requeried using the Requery method. The Requery method resets the absolutePosition (bookmark) from the newly inserted record, to the first record of the requeried recordset. As a result, the absolutePosition must be saved before calling Requery, and restored to the newly inserted record after Requery has been called. ' when you invoke the method AddNew it adds a new record to the end of ' your current recordset and places your cursor on that record. when you invoke the method Update, it updates the database with the ' values of the new record that we just created. To retrieve the ' value of the Autonumber field we need to update the ADO recordset that ' currently have. ' When you do a Requery on your recordset, you lose your cursor. So ' we need to store the location before we do the Requery, then reset ' it after the Requery. 'before the requery, the Autonumber field shows as 0 ' First, store the location of you cursor bookmark = objRS.absolutePosition objRS.Requery ' Next, update your recordset with the data from the database 'after the requery, the absolutePosition is the first record of the recordset objRS.absolutePosition = bookmark ' Finally, change your cursor back 'now we have the Autonumber value |
Q | ACCESS 97设置密码后在 VC 中如何调用!??? |
T | ACCESS 97设置密码后在 VC 中如何调用!??? 在VC中通过CDaoDatabase系列来调用ACCESS 97 数据库,为了数据安全, 我需要对数据库加密,并且设置了密码,请问: 如何实现设置密码后的VC调用??? 谢谢 |
A | // The following code presents several functions you can use to manage // MFC DAO classes in a way that allows you to call the DAO interfaces. // It then shows how to use those functions within InitInstance(). // Set the system database that the DAO database engine will use: void AfxDaoSetSystemDB(CString & strSystemMDB) { COleVariant varSystemDB(strSystemMDB,VT_BSTRT ); // Initialize DAO for MFC: AfxDaoInit(); DAODBEngine* pDBEngine = AfxDaoGetEngine(); ASSERT(pDBEngine != NULL); // Call put_SystemDB method to set the system database for DAO engine: DAO_CHECK( pDBEngine->put_SystemDB( varSystemDB.bstrVal ) ); } void AfxDaoSetDefaultUser(CString & strUserName, CString & strPassword) { COleVariant varUserName( strUserName, VT_BSTRT ); COleVariant varPassword( strPassword, VT_BSTRT ); DAODBEngine* pDBEngine = AfxDaoGetEngine(); ASSERT(pDBEngine != NULL); // Set default user: DAO_CHECK( pDBEngine->put_DefaultUser(varUserName.bstrVal)); // Set default password: DAO_CHECK( pDBEngine->put_DefaultPassword(varPassword.bstrVal)); } void AfxDaoChangePassword(CString & strUserName, CString & strOldPassword, CString & strNewPassword) { // Create(Open) Workspace: CDaoWorkspace wsp; CString strWspName = _T("Temp Workspace"); wsp.Create( strWspName, strUserName, strOldPassword ); wsp.Append(); // Determine how many objects there are in the Users collection: short nUserCount; short i; DAOUser *pUser = NULL; DAOUsers *pUsers = NULL; // Side-effect is implicit OLE AddRef() on DAOUser object: DAO_CHECK( wsp.m_pDAOWorkspace->get_Users( &pUsers ) ); // Side-effect is implicit OLE AddRef() on DAOUsers object: DAO_CHECK( pUsers->get_Count( &nUserCount ) ); TRACE( "# of users in collection = %d/n", nUserCount ); // Traverse through the list of users and change password for userid // used to create/open the workspace: for( i = 0; i < nUserCount; i++ ) { COleVariant varIndex( i, VT_I2 ); COleVariant varName; // Retrieve information for user i DAO_CHECK( pUsers->get_Item( varIndex, &pUser ) ); // Retrieve name for user i DAO_CHECK( pUser->get_Name( &V_BSTR(&varName)) ); TRACE( "User # %d Name = %s/n", i, V_BSTRT(&varName) ); CString strTemp = V_BSTRT(&varName); // If there is a match, change the password: if( strTemp == strUserName ) { COleVariant varOldPwd( strOldPassword, VT_BSTRT ); COleVariant varNewPwd( strNewPassword, VT_BSTRT ); DAO_CHECK( pUser->NewPassword( V_BSTR( &varOldPwd ), V_BSTR( &varNewPwd ) ) ); TRACE( "/t Password is changed/n" ); } } // Clean up: decrement the usage count on the OLE objects: pUser->Release(); pUsers->Release(); wsp.Close(); } BOOL CMyApp::InitInstance() { // Specify path to the Microsoft Access system database: CString strSystemDB = _T("c://Program Files//MSOffice//access//System.mdw"); // Set system database before MFC initilizes DAO: AfxDaoSetSystemDB(strSystemDB); // User name and password manually added by using Microsoft Access: CString strUserName = _T("NewUser"); CString strOldPassword = _T("Password"); CString strNewPassword = _T("NewPassword"); // Set default user so that MFC will be able to log in by default // using the user name and password from the system database: AfxDaoSetDefaultUser(strUserName,strOldPassword); // Change the password. You should be able to call this function from // anywhere in your MFC application: ChangePassword(strUserName,strOldPassword,strNewPassword); // Remainder of your InitInstance code: ... } |