Tibero OLE DB User Guide - Technet
Transcription
Tibero OLE DB User Guide - Technet
— Development and Operation — Tibero OLE DB User Guide 2014. 05. 16. Development and Operation Better Technology, Better Tomorrow Table of Contents 1. Definition ..................................................................................................................................................................................................................4 1.1. What is OLE DB (Object Linking and Embedding, Database)? ..........................................................................................................4 1.2. ADO (ActiveX Data Objects) .......................................................................................................................................................................4 1.3. Role of OLE DB ..............................................................................................................................................................................................4 1.4. OLE DB Internal Structure ..........................................................................................................................................................................5 2. OLE DB Provider Installation and Environment Configuration ....................................................................................................................6 2.1. Checking Tibero OLE DB Driver.................................................................................................................................................................6 2.2. Registering Tibero OLE DB Driver .............................................................................................................................................................6 2.3. OLE DB Driver Connection .........................................................................................................................................................................7 2.4. Installing OLE DB in a Windows 64-bit Environment ..........................................................................................................................9 2.5. Testing Tibero OLE DB Integration in a Windows 64-bit Environment ........................................................................................ 11 2.6. Installing ODBC Using Tibero ODBC Installer ..................................................................................................................................... 11 2.7. Configuring Environment Variables for Debugging ........................................................................................................................... 14 3. Connection String ................................................................................................................................................................................................ 15 3.1. Configuration Items .................................................................................................................................................................................. 15 3.2. Description of Additional Items ............................................................................................................................................................. 15 3.3. Creating Connection Strings ................................................................................................................................................................... 16 4. ADO and .NET Provider Integration ................................................................................................................................................................ 16 4.1. ADO (ActiveX Data Objects) .................................................................................................................................................................... 16 4.2. Major ADO Objects ................................................................................................................................................................................... 17 4.3. Cursor Location .......................................................................................................................................................................................... 18 5. Special Features ................................................................................................................................................................................................... 19 5.1. Updatable Cursor ...................................................................................................................................................................................... 19 5.2. Schema Rowset .......................................................................................................................................................................................... 20 5.3. Connection Pooling ................................................................................................................................................................................... 20 6. Trouble Shooting ................................................................................................................................................................................................. 20 6.1. Error Message Handling .......................................................................................................................................................................... 20 6.2. Points to Consider when Installing IIS+MS Office (Excel) ................................................................................................................ 20 6.3. UTF8 Broken Characters .......................................................................................................................................................................... 21 6.4. Tbprov vs MSDTB ...................................................................................................................................................................................... 21 7. Adding Tibero DLL files in Visual Studio (C#) ............................................................................................................................................... 22 7.1. How to add Tibero.DbAccess.dll and EntLibContrib.Data.Tibero.dll ............................................................................................ 22 8. OLE DB Migration ................................................................................................................................................................................................ 23 8.1. Migrating from Oracle to Tibero ........................................................................................................................................................... 23 9. Examples................................................................................................................................................................................................................ 25 9.1. ASP Sample Source (SELECT) .................................................................................................................................................................. 25 2 Development and Operation Better Technology, Better Tomorrow 9.2. Procedure Request and CLOB Handling ............................................................................................................................................... 26 9.3. VBScript Sample Source (SELECT) ......................................................................................................................................................... 28 9.4. C# Sample Source (SELECT)..................................................................................................................................................................... 28 9.5. C# Sample Source 2 (Retrieving a data column name) .................................................................................................................... 30 9.6. ASP.NET WITH C# ....................................................................................................................................................................................... 30 9.7. C# WITH Enterprise Library..................................................................................................................................................................... 34 9.8. C# Named Parameter Sample ................................................................................................................................................................ 41 9.9. Decompiling C# (ildasm) .......................................................................................................................................................................... 42 9.10. C# (Procedure returns cursor-SYS_REFCURSOR) ............................................................................................................................. 42 9.11. C# (Procedure returns cursor - REF CURSOR) .................................................................................................................................. 43 9.12. ASP (BLOB Insert Sample) ..................................................................................................................................................................... 46 3 Development and Operation Better Technology, Better Tomorrow Tibero OLE DB User Guide This document describes the features of Tibero OLE DB and includes its definition, configuration, integration, functions, error handling, and sample source. 1. Definition 1.1. What is OLE DB (Object Linking and Embedding, Database)? ODBC enables applications to access databases through a common abstract API regardless of language, table structure, or data type. Due to developments in IT, ODBC has become unsuitable when new methods are used to design and build DB-based applications. In response, OLE DB, an open DB connection, was created. OLE DB is a programing interface model that reifies the concept of Microsoft Universal Data Access (UDA). UDA provides a function to access relational, non-relational, and hierarchical data using a single COM based programing interface. Tibero OLE DB Provider currently supports the Windows operating system. Tibero OLE DB Provider guarantees performance and stability of the environment used by ADO or OLE DB based applications to access the Tibero database. Tibero OLE DB Provider is compatible with the latest OLE DB and ADO specifications so ADO or OLE DB developers can easily migrate applications to the Tibero environment. Additionally, Tibero OLE DB Provider enables functions, such as PSM saving procedure and LOB, to be utilized. Tibero OLE DB also fully supports the .NET environment using the Microsoft OLE DB.NET data provider. When OLE DB .NET is used, it is possible to access a Tibero database using various .NET programing languages. 1.2. ADO (ActiveX Data Objects) While OLE DB is a technology that provides an interface to access a RDBMS or non-relational database, ADO is an advanced version of the technology that enables data input and inquiries via the interface. 1.3. Role of OLE DB OLE DB provides a comprehensive view of distributed data. UDA can access non-SQL data (mail, text, and directory services) as well as SQL data using ADO and OLED. OLE DB can use the same data connection as the existing ODBC. Accessing with OLE DB improves connection speed by complementing the existing ODBC‘s deficiencies. 4 Development and Operation Better Technology, Better Tomorrow (Excerpt) uda architecture http://msdn.microsoft.com/en-us/library/windows/desktop/ms709836(v=vs.85).aspx 1.4. OLE DB Internal Structure - Initializes the OLE DB provider and configures the environment. More than one connection (Session) can be created after receiving access information. - A session is a connection. A session usually creates more than one command and result table (Rowset). - A SQL statement that creates multiple Rowsets when there are multiple SELECT statements. - A set of data (rows) from a database. Forward, reverse, and specific row access are supported. An application accesses the data source through OLE DB API in the following order. 1. Initializes an OLE DB. 2. Connects to a data source 3. Issues a command. 4. Processes the results. 5. Releases the data source object and uninitializes the OLE DB. 5 Development and Operation Better Technology, Better Tomorrow 2. OLE DB Provider Installation and Environment Configuration 2.1. Checking Tibero OLE DB Driver To install Tibero OLE DB for Windows, the following files are required. Contact an administrator to receive the files. • odbc_driver_install.exe: Tibero ODBC Driver Installer provided by the ODBC administrator. • vcredist.EXE: Install Microsoft Visual C++ 2005 Redistribution if necessary. • libtbcli.dll: ODBC driver of Tibero • libtbcli.lib: ODBC library of Tibero • tbprov.dll: Tibero OLE DB Provider driver (tbprov5.dll for r67771 or above) • tbprov.lib: Tibero OLE DB Provider library (tbprov5.dll for r67771 or above) • msdtb.dll: Tibero OLE DB Provider(MSDTB) driver (tbprov5.dll for r67771 or above) • msdtb.lib: Tibero OLE DB Provider(MSDTB) library (tbprov5.dll for r67771 or above) The OLE DB driver or library can also be found in the $TB_HOME/client/win32/lib/oledb directory of the Tibero engine. 2.2. Registering Tibero OLE DB Driver Copy the Tibero OLE DB driver into the C:\Windows\system32 directory and enter the following commands in the command line. ODBC OLE DB libtbcli.dll msdtb.dll (msdtb5.dll for Tibero 5 r67771 or above) msdtb.pdb (may not exist depending on the release version) tbprov.dll (msdtb5.dll for Tibero 5 r67771 or above) tbprov.pdb (may not exist depending on the release version) Registry Registration Commands [Description of the pdb file] File with a PDB extension (Program Database) - Debugging files - The contents included in the PDB formatted file are local variable name, source files name, source line number and source indexing. Tibero.DbAccess.dll (Definition of .NET data type) EntLibContrib.Data.Tibero.dll (Included when MS Enterprise Library is used) regsvr32 tbprov.dll (tbprov5.dll for Tibero 5 r67771 or above) regsvr32 msdtb.dll (msdtb5.dll for Tibero 5 r67771 or above) Registry Deregistration Commands regsvr32 /u tbprov.dll (tbprov5.dll for Tibero 5 r67771 or above) regsvr32 /u msdtb.dll (msdtb5.dll for Tibero 5 r67771 or above) Others Register the ODBC using the ‘tbodbc_driver_installer_5_32.exe’ file. Location of the libtbcli.dll file must be appended. (E.g., tbodbc_driver_installer_5_32.exe -i C:\Windows\system32) 6 Development and Operation Better Technology, Better Tomorrow 2.3. OLE DB Driver Connection ① Create a file on the desktop and name it tibero.udl. ② Double click the tibero.udl file and select [Provider] to see Tibero OLE DB Provider. ③ The following describes three ways to perform the connection test using the tibero.udl file. Direct Connection using IP or Port in Location Configure Tibero IP and PORT information, User Name, and Password to log onto the server. Click the Test Connection button. (IP and Port must be separated by a comma.) 7 Development and Operation Better Technology, Better Tomorrow [Example] ## OLEDB Connection String (using Tibero IP&Port)## Connection String for Tibero OLE DB Provider (Default) Provider=tbprov.Tbprov;Location=127.0.0.1,8629;User ID=sys;Password=tibero; Connection String to replace ‘Microsoft OLE DB Provider for Oracle’ Provider=tbprov.MSDTB;Location=127.0.0.1,8629;User ID=sys;Password=tibero; Using DSN of the ODBC source administrator or Alias of tbdsn.tbr Tibero can be accessed by using the DSN of the ODBC source administrator or the alias of "$TB_HOME/client/config/tbdsn.tbr". The applicable alias information can be found under [ODBC Source Administrator] > [Alias of tbdsn.tbr]. [Example] ## OLEDB Connection String (using DSN or the alias in tbnet_alias.tbr file) ## Connection String for Tibero OLE DB Provider (Default) Provider=tbprov.Tbprov;Data Source=tibero;User ID=sys;Password=tibero; Connection String to replace ‘Microsoft OLE DB Provider for Oracle’ Provider=tbprov.MSDTB;Data Source=tibero;User ID=sys;Password=tibero; 8 Development and Operation Better Technology, Better Tomorrow Connection using IP, PORT, and DBNAME in Data Source (Tibero 5) Access Tibero by setting the IP, PORT, and DB NAME (in this order). The items can be separated by commas. ## OLEDB Connection String## Connection String for Tibero OLE DB Provider (Default) Provider=tbprov.Tbprov; Data Source='127.0.0.1,8629,tibero';User ID=sys;Password=tibero; Connection String to replace ‘Microsoft OLE DB Provider for Oracle’ Provider=tbprov.MSDTB; Data Source='127.0.0.1,8629,tibero' 2.4. Installing OLE DB in a Windows 64-bit Environment The following is the process for registering the OLE DB driver in a Windows 64-bit environment. (Windows 2003, Windows 2008, etc.) Since the Windows 64-bit environment basically uses a 32-bit client library, an additional step for configuring the 32-bit client library is required. ① Copy the files located in %TB_HOME%client\lib\win32\’ to ‘C:\Windows\SysWow64\’ . ODBC OLE DB Others libtbcli.dll msdtb.dll (msdtb5.dll for Tibero 5 r67771 or above) msdtb.pdb tbprov.dll (tbprov5.dl l for Tibero 5 r67771 or above) tbprov.pdb Tibero.DbAccess.dll (.NET Provider) EntLibContrib.Data.Tibero.dll (Included when MS Enterprise Library is used) ② Register the tbprov and msdtb libraries using regsvr32.exe located in ‘C:\Windows\SysWow64\'. (E.g., regsvr32 tbprov.dll, regsvr32 msdtb.dll) (regsvr32 tbprov5.dll, regsvr32 msdtb5.dll for Tibero 5 r67771 or above) 9 Development and Operation Better Technology, Better Tomorrow ③ Register OLE DB using the ‘tbodbc_driver_installer_5_64.exe’ file, and specify the path to the directory where the libtbcli.dll file exists. (E.g., tbodbc_driver_installer_5_64.exe-i C:\Windows\SysWow64) ④ After the ODBC driver is installed, run the odbcad32 file located in the directory to register a DSN. (When the file is run, the 32-bit ODBC Data Source Administrator screen appears.) 10 Development and Operation Better Technology, Better Tomorrow 2.5. Testing Tibero OLE DB Integration in a Windows 64-bit Environment ① Create the tibero.udl file in the C:\ directory. ② Run the following command after opening a command window. C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll", OpenDSLFile C:\tibero.udl ● Note A connection pooling function is provided by the driver. Tibero provides the connection pooling function for OLE DB, ODBC, and .Net Framework Data Provider for Oracle, which are provided by MicroSoft. The following shows how to use the connection pooling function. //OLE DB Services=-1 (uses pooling) //OLE DB Services=-2 (does not use pooling. Default Value) Provider=tbprov.Tbprov;Data Source='tibero';User ID=sys;Password=tibero; Services=-1 OLE DB ** Since the default value of connection pooling depends on the development language, check the default value before applying it. (In the above example, the default value of connection pooling is C#.) 2.6. Installing ODBC Using Tibero ODBC Installer OS BIT 32 BIT 64 BIT Location Contact the administrator. Contact the administrator. Run the applicable installation file. 11 Installer TiberoODBC32_Setup.exe TiberoODBC64_Setup.exe Development and Operation Better Technology, Better Tomorrow - Select a language. - Select ‘Install’ and click the [Next] button to continue. - Check the packs to be installed and click the [Next] button to continue. 12 Development and Operation Better Technology, Better Tomorrow - Click the [Browse...] button and select the desired folder. - After installation is complete, click the [Next] button. - The installed ODBC and OLE DB drivers are now registered to Windows. 13 Development and Operation Better Technology, Better Tomorrow - After the modules are successfully registered, the following screen appears. 2.7. Configuring Environment Variables for Debugging When the following environment variables are specified in the system environment variable for debugging, the logs can be checked. Category ODBC OLE DB Environment Variable TBCLI_LOG_DIR TBCLI_LOG_LVL TB_OLEDB_LOG Description Log creation directory FATAL, ERROR, WARN, DEBUG, TRACE 0~4 Default : 0 14 Development and Operation Better Technology, Better Tomorrow 3. Connection String The information required to access OLE DB are Provider, Data Source, Location, User ID, and Password. 3.1. Configuration Items Basic Items Additional Items Provider Name Provider, Data Source, Location, User ID, Password Updatable Cursor, OLE DB Services Tibero 5 before r67770 Tibero 5 r67770 and above tbprov.Tbprov No changes tbprov.Tbprov.1 tbprov.Tbprov.5 tbprov.MSDTB No changes tbprov.MSDTB.1 tbprov.MSDTB.5 Data Source Name - The name registered in the ODBC Data Source Administrator - tibero5 Data Source=ip,port, dbname - tibero4 Data Source=ip,port Location - IP and PORT are required. Separate IP and PORT with a comma. [Example] Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax Provider=tbprov.Tbprov.1;Data Source=127.0.0.1,8629,tibero; User ID=tibero;Password=tmax Provider=tbprov.MSDTB.1;Location=192.168.1.83,8629;User ID=tibero;Password=tmax 3.2. Description of Additional Items Item Updatable Cursor Option True | False Default False Description Option to use updatable cursors OLE DB Services -1 | -2 -1 Option to use connection pooling function -1: uses pooling -2: does not use pooling Example “Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax; Updatable Cursor=True;OLE DB Services=-2” 15 Development and Operation Better Technology, Better Tomorrow 3.3. Creating Connection Strings - How to Use: Extract the connection string by creating a file with the UDL extension. (E.g., a.udl) - Problems: Configuring extraneous items may generate complex strings. - Recommendation: Use only required items. 4. ADO and .NET Provider Integration 4.1. ADO (ActiveX Data Objects) ADO (ActiveX Data Object) is an interface that integrates with a database developed by Microsoft. Multiple tasks can be carried out after accessing the database using the ADO component. – A set of COM objects to access the database. – A connecting layer that links the user’s programing language with OLE DB. – It is installed automatically when the Windows operating system is installed. – It is available in ASP, PHP, and VB. – Users have the option to use the simplified ADO API rather than the complicated OLE DB API for development. – It is integrated with diverse script languages so can be developed in multiple environments. 16 Development and Operation Better Technology, Better Tomorrow 4.2. Major ADO Objects Object Connection Description Used to connect to a database. Set conn=Server.CreateObject(“ADODB.Connection”); Recordset Used to return data from a lookup query.Set rs = Server.CreateObject(“ADODB.Recordset”) rs.open “select * from emp”,conn Command This object is used for database connection, command, or query execution. It is generally used when a query that includes procedure execution or parameters is executed. Set Cmd = Server.CreateObject("ADODB.Command") with Cmd .ActiveConnection = objConn .CommandType = adCmdStoredProc .CommandText = "ADD" … End with Set Cmd = Nothing Transaction The transactions being used are located between .BeginTrans of the connection object and the .CommitTrans method request. myConnection.BeginTrans While Not myRecordset.EOF mcounter = mcounter + 1 myRecordset.Update myRecordset.MoveNext Wend myConnection.CommitTrans myRecordset.Close myConnection.Close Property Contains the dynamic properties of the ADO object. set prop=Server.CreateObject("ADODB.Property") for each prop in rs.Properties response.write("Attr:" & prop.Attributes & "<br>") response.write("Name:" & prop.Name & "<br>") response.write("Value:" & prop.Value & "<br>") next Field The ADO Field object contains information about columns in the Recordset object. 17 Development and Operation Better Technology, Better Tomorrow set f=Server.CreateObject("ADODB.Field") for each f in rs.Fields response.write("Attr:" & f.Attributes & "<br>") response.write("Name:" & f.Name & "<br>") response.write("Value:" & f.Value & "<br>") Next Provides information about the stored procedure or the parameters used in a query. (Parameter Type: input, output, input/output, and return) Parameter set comm=Server.CreateObject("ADODB.Command") set para=Server.CreateObject("ADODB.Parameter") para.Type=adVarChar para.Size=20 para.Direction=adParamInput para.Value=username comm.Parameters.Append para Error Saves errors that occur during execution in the errors collection. for each objErr in objConn.Errors response.write("<p>") response.write("Description: ") response.write(objErr.Description & "<br>") response.write("Help context: ") response.write(objErr.HelpContext & "<br>") response.write("Help file: ") response.write(objErr.HelpFile & "<br>") response.write("Native error: ") response.write(objErr.NativeError & "<br>") response.write("Error number: ") response.write(objErr.Number & "<br>") response.write("Error source: ") response.write(objErr.Source & "<br>") response.write("SQL state: ") response.write(objErr.SQLState & "<br>") response.write("</p>") next Record Holds one row in a file, directory, or Recordset in the file system. countfields=rec.Fields.Count 4.3. Cursor Location A cursor location can be configured by connection or Recordset. adUseNode - OBSOLETE (Exists only for backward compatibility). - Value 1 adUseServer (Default) - Whenever a user goes to another row, it brings data from OLE DB. 18 Development and Operation Better Technology, Better Tomorrow - Better performance when only some of rows are selected. (The total memory usage is less.) - Data cannot be selected after disconnecting. - Updatable cursors are supported. - Value 2 adUseClient - It brings all data from OLE DB and saves it in ADO to use whenever a user goes to another row using the ADO function. - Because necessary data is already selected, the data is accessible even after disconnecting. - Updatable cursors are not supported. -Value 3 [Usage Example-vbscript] Dim conn, rs, sql Set conn = CreateObject("ADODB.Connection") conn.Open "Provider=tbprov.Tbprov.1;Data Source=4;User ID=tibero;Password=tmax;" conn.CursorLocation = adUseClient 'adUseServer = 2, adUseClient = 3 Set rs = CreateObject("ADODB.RecordSet") sql = "select sysdate from dual" rs.Open sql, conn While Not rs.EOF WScript.Echo rs("sysdate") rs.MoveNext Wend rs.Close() Set rs = Nothing Set conn = Nothing 5. Special Features 5.1. Updatable Cursor As a result of queries, it modifies table data and applies it to the server. A query is sent with a rowid by default. A query that cannot have a rowid attached cannot be an updatable cursor. Addition, deletion, and modification are written with DML using rowid and sent to servers. Adding a new row The added row is not saved in the result table. Deleting a row The deleted row is flagged for deletion. Modifying the data of a row The modified data can be checked immediately. [Example-PHP] $conn = new COM("ADODB.Connection"); $conn->Open("Provider=tbprov.Tbprov.1; Data Source=tibero; User ID=SYS; Password=tibero;Updatable Cursor=True;“); $rs = new COM("ADODB.Recordset"); $rs->CursorLocation = adUseServer; $rs->Open("for_member", $conn, adOpenKeyset, adLockPessimistic, adCmdTable); $rs->MoveNext(); $rs->Fields("EMAIL")->value = "[email protected]"; $rs->Fields("PASSWORD")->value = "tmax123"; $rs->Fields("NAME")->value = “TESTUSER”; $rs->Update(); $rs->Close(); 19 Development and Operation Better Technology, Better Tomorrow 5.2. Schema Rowset It shows the schema information of the database (tables and procedures) in the form of a table. Schema Rowset usually queries the static view of the database, extracts the target information, and stores and extracts the target schema information in OLE DB. [Example-PHP] $conn = new COM("ADODB.Connection"); $conn->Open(“Provider=tbprov.Tbprov.1; …”); $arr[0] = ""; $arr[1] = “SCOTT“; $arr[2] = “EMP"; $rs = new COM("ADODB.Recordset"); $rs->CursorLocation = adUseClient; $rs = $conn->OpenSchema(adSchemaPrimaryKeys, $arr); 5.3. Connection Pooling It saves existing connections and reuses them when the same account makes repeated connections. This reduces the time to connect. How to Configure Add OLE DB services to the connection string. OLE DB Services=-1 (uses pooling) OLE DB Services=-2 (does not use pooling.) For PHP, configure to use it unconditionally 6. Trouble Shooting 6.1. Error Message Handling Current cursor is not updatable (tberr 2135) Error 1 Error 2 This occurs when an updatable cursor is inactive How to respond: add “Updatable Cursor=True” to the connection string. Updatable cursor query is unavailable. Target: - When the query cannot use a rowid. - When the “join string” is in a query that defines “view”. Resolution: - Write a replacement query. - Manually write DML to modify. 6.2. Points to Consider when Installing IIS+MS Office (Excel) The IIS server operates abnormally when Excel or other office programs are installed. [Error 1] The ASP page displays the error ‘Cannot find provider’. [Error 2] If Tibero OLE DB or ODBC is reinstalled and tested when error 1 occurs, the session between ASP and Tibero disconnects immediately after connecting. 20 Development and Operation Better Technology, Better Tomorrow [Resolution] Remove the IIS server to reinstall. (Installing office programs updates the DLL and ODBC settings for the IIS server.) 6.3. UTF8 Broken Characters Application ---------- enterprise library -------- tboledb ------- tbcli --------- tibero server The error can occur when an application displays UTF8 data from the database as UCSI on the screen. This is because UTF 8 is bound wchar (ucs2 unicode) when Oracle sends UTF8 data to the enterprise library. (Resolution 1) Replace char and varchar with nchar and nvarchar. (Resolution 2) Set TB_NLS_LANG to the character set used by the Windows system executing the application. (Resolution 3) Replace UTF8 with wchar(ucs2 unicode)in the application. (Resolution4) Configure the environment variable that forcefully binds char and varchar to wchar as follows. (Tibero5 r70330 or above) FORCED_USE_WCHAR=1 6.4. Tbprov vs MSDTB Tbprov MSDTB Binary that meets the OraOLEDB’s data type specifications. Binary that meets the MSDAORA’s data type specifications. Data Types of ADO Tibero type NUMBER NUMBER(p,s) CHAR VARCHAR ADO type (Tbprov) adDouble=5 adNumeric=131 adWChar=130 adVarWChar=202 ADO type (MSDTB) adVarNumeric=139 adNumeric=131 adChar=129 adVarChar=200 ParameterDirectionEnum Values Specifies whether the Parameter represents an input parameter, an output parameter, both an input and an output parameter, or the return value from a stored procedure. Constant Value Description adParamUnknown 0 Direction is unknown adParamInput 1 Input parameter adParamOutput 2 Output parameter adParamInputOutput 3 Both input and output parameter adParamReturnValue 4 Return value [Constant Value of Data Type] Constant adEmpty adSmallInt adInteger adSingle adDouble adCurrency adDate day. adBSTR adIDispatch Value 0 2 3 4 5 6 7 Description No value A 2-byte signed integer. A 4-byte signed integer. A single-precision floating-point value. A double-precision floating-point value. A currency value The number of days since December 30, 1899 + the fraction of a 8 9 A null-terminated character string. A pointer to an IDispatch interface 21 on a COM object. Note: Development and Operation Better Technology, Better Tomorrow Currently not supported by ADO. adError 10 A 32-bit error code adBoolean 11 A boolean value. adVariant 12 An Automation Variant. Note:Currently not supported by ADO. adIUnknown 13 A pointer to an IUnknown interface on a COM object. Note: Currently not supported by ADO. adDecimal 14 An exact numeric value with a fixed precision and scale. adTinyInt 16 A 1-byte signed integer. adUnsignedTinyInt 17 A 1-byte unsigned integer. adUnsignedSmallInt 18 A 2-byte unsigned integer. adUnsignedInt19 A 4-byte unsigned integer. adBigInt 20 An 8-byte signed integer. adUnsignedBigInt 21 An 8-byte unsigned integer. adFileTime 64 The number of 100-nanosecond intervals since January 1,1601 adGUID 72 A globally unique identifier (GUID) adBinary 128 A binary value. adChar 129 A string value. adWChar 130 A null-terminated Unicode character string. adNumeric 131 An exact numeric value with a fixed precision and scale. adUserDefined132 A user-defined variable. adDBDate 133 A date value (yyyymmdd). adDBTime 134 A time value (hhmmss). adDBTimeStamp135 A date/time stamp (yyyymmddhhmmss plus a fraction in billionths). adChapter 136 A 4-byte chapter value that identifies rows in a child rowset adPropVariant138 An Automation PROPVARIANT. adVarNumeric 139 A numeric value (Parameter object only). adVarChar 200 A string value (Parameter object only). adLongVarChar201 A long string value. adVarWChar 202 A null-terminated Unicode character string. adLongVarWChar 203 A long null-terminated Unicode string value. adVarBinary 204 A binary value (Parameter object only). adLongVarBinary 205 A long binary value. AdArray 0x2000 A flag value combined with another data type constant. Indicates an array of that other data type. 7. Adding Tibero DLL files in Visual Studio (C#) 7.1. How to add Tibero.DbAccess.dll and EntLibContrib.Data.Tibero.dll Select [Solution Explorer] > [Reference] > [Add Reference] Select Tibero.DbAccess.dll and EntLibContrib.Data.Tibero.dll in [Add Reference] > [Browse]. 22 Development and Operation Better Technology, Better Tomorrow The following lines must be included in the source code. (C#) using EntLibContrib.Data.Tibero; using Tibero.DbAccess; 8. OLE DB Migration 8.1. Migrating from Oracle to Tibero Oracle Tibero OracleConnection OleDbConnectionTbr OracleCommand OleDbCommandTbr OracleDataReader OleDbDataReader OracleDataAdapter OleDbDataAdapterTbr OracleDbType OleDbTypeTbr OracleParameter OleDbParameterTbr OracleCommandBuilder OleDbCommandBuilderTbr OracleTransaction OleDbTransaction 23 Development and Operation Better Technology, Better Tomorrow OracleLob OleDbYpeTbr.LongVarChar (Corresponding CLOB) or OleDbTypeTbr.LongVarBinary (Corresponding BLOB) [Usage Instructions] After reading from a reader, use GetString to read. E.g., if (reader.Read()) { string clob = reader.GetString(0); .. } Add the Tibero OLE DB settings to [web.config] or [app.config]. <connectionStrings> <add name="oracle_con" connectionString="Data Source=CENT64_JP2;Persist Info=True;User ID=scott;Password=tiger" providerName="System.Data.OracleClient" /> <add name="tibero5_odbc" connectionString="DRIVER={Tibero 5 Driver};SERVER=127.0.0.1;PORT=8629;DB=tibero;UID=sysadm;PWD=sysadm" providerName="System.Data.Odbc" /> <add name="tibero5_oledb" connectionString="Provider=tbprov.Tbprov.1; Data Source=tibero;User ID=tibero; Password=tmax; Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> </connectionStrings> Security ODBC Add the following settings when Enterprise Library is used and accessed by applications. [App.config Example] <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" /> </configSections> <dataConfiguration defaultDatabase="tibero"> <providerMappings> <add databaseType="EntLibContrib.Data.Tibero.TiberoDatabase, EntLibContrib.Data.Tibero, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Tibero.DbAccess" /> </providerMappings> </dataConfiguration> <connectionStrings> <add name="tibero" connectionString="Provider=tbprov.Tbprov.1;Data Source=tibero5;User ID=sys;Password=tibero;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" 24 Development and Operation Better Technology, Better Tomorrow providerName="Tibero.DbAccess" /> </connectionStrings> </configuration> Oracle selectCmd.Parameters.Add("rs_Lst", OracleDbType.RefCursor).Direction= ParameterDirection.Output; OracleParameter a = new OracleParameter("i_fromdate", fromdate); a.Direction = ParameterDirection.Input; a.OracleType = OracleType.VarChar; Tibero OleDbCommandTbr selectCmd = new OleDbCommandTbr(); selectCmd.Connection = oConn; selectCmd.CommandType = CommandType.StoredProcedure; selectCmd.CommandText = "PKG_CRM_AnalysisTBR.Get_Cust_Crm_Sex_List selectCmd.Parameters.Add("rs_Lst", OleDbTypeTbr.Cursor).Direction = ParameterDirection.Output; OleDbParameterTbr a = new OleDbParameterTbr("i_fromdate", fromdate); a.Direction = ParameterDirection.Input; a.OleDbType = OleDbTypeTbr.VarChar; OracleParameter b = new OracleParameter ("o_rc", DBNull.Value); b.Direction = ParameterDirection.Output; b.OracleType = OracleType.RefCursor; OleDbParameterTbr b = new OleDbParameterTbr("o_rc", DBNull.Value); b.Direction = ParameterDirection.Output; b.OleDbType = OleDbTypeTbr.Cursor; selectCmd.Parameters.Add(a); selectCmd.Parameters.Add(b); selectCmd.Parameters.Add(a); selectCmd.Parameters.Add(b); The ‘Bind by name’ function (Supported in the .NET provider layer. Unsupported in ODBC) OleDbCommandTbr oCmd = new OleDbCommandTbr(); oCmd.Connection = oConn; oCmd.CommandType = CommandType.Text; oCmd.CommandText = "insert into aaa(aa,bb) values (:aa,:bb)"; oCmd.Parameters.Add(new OleDbParameterTbr("bb", "bb")); oCmd.Parameters.Add(new OleDbParameterTbr("aa", "aa")); 9. Examples 9.1. ASP Sample Source (SELECT) <%@ Language=VBScript %> <%Option Explicit%> <HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> </HEAD> <BODY> <table style="font-size:10pt" border="1"> <% Dim Con, Rs Set Con = Server.CreateObject ("ADODB.Connection") Con.Open "Provider=tbprov.Tbprov.1;Password=tibero;Persist 25 Security Info=True;User Development and Operation Better Technology, Better Tomorrow ID=SYS;Data Source=tibero" // Open the .UDL file with a text viewer to copy the contents. Set Rs = Con.Execute ("Select * From user_objects") while not Rs.eof %> <TR> <TD><%=Rs("OBJECT_NAME")%></TD> <TD><%=Rs("OBJECT_ID")%></TD> <TD><%=Rs("OBJECT_TYPE")%></TD> <TD><%=Rs("OBJECT_TYPE_NO")%></TD> <TD><%=Rs("CREATED")%></TD> <TD><%=Rs("STATUS")%></TD> <TD><%=Rs("TEMPORARY")%></TD> </TR> <% rs.movenext wend Set Rs = Nothing Con.Close Set Con = Nothing %> </table> </BODY> </HTML> 9.2. Procedure Request and CLOB Handling [Table] create table notice (seq number, contents clob); [Procedure] CREATE or replace PROCEDURE UPDATE_NOTICE ( V_SEQ IN number , V_CONTENTS IN CLOB ) AS loba clob BEGIN insert into notice(SEQ, CONTENTS) values(V_SEQ, EMPTY_CLOB()); select contents into loba from notice where seq=v_seq; dbms_lob.write(loba,length(v_contents),1,v_contents); COMMIT; END; [ASP] <%@ CodePage=51949 Language="VBScript"%> <% Set objConn = server.CreateObject("ADODB.Connection") ‘objConn.Open "Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax;" objConn.Open "Provider=MSDASQL;DSN=tibero;UID=tibero;PWD=tmax;" Set cmd= Server.CreateObject("ADODB.Command") contents = "aaaaaaaaaaaaaaaaaaaaaa" with cmd 26 Development and Operation Better Technology, Better Tomorrow set .ActiveConnection = objConn .CommandType = 4 .CommandText = "UPDATE_NOTICE" .Parameters.Append .CreateParameter("@V_SEQ",3, 1, 4) .Parameters.Append .CreateParameter("@V_CONTENTS", Len(contents)) .Parameters("@V_SEQ") = 4 .Parameters("@V_CONTENTS") = contents .Execute end with 201, 1, Set cmd = Nothing objConn.Close response.Write("sql : " & Sql & "<br>") %> [CLOB SELECT] <% Dim Con, Rs, strQry Set Con = Server.CreateObject ("ADODB.Connection") Con.Open "Provider=MSDASQL;DSN=tibero;UID=tibero;PWD=tmax;" Set Rs = Server.CreateObject("ADODB.Recordset") Function CLOBRead(pLen, seq) Dim K Dim strMok Dim strLast Dim strReturn Dim Res strMok = int(Clng(pLen) / 2000) strLast = int(strMok + 1) Set Res = Server.CreateObject("ADODB.Recordset") For K = 1 To strLast sQuery = "" sQuery = sQuery & " SELECT DBMS_LOB.SUBSTR(CONTENTS, 2000, 2000 * (" & K & " - 1) + 1) MEMO FROM NOTICE where seq=" & seq & vbCrLf Res.Open sQuery, Con strReturn = strReturn & Res("memo") Res.Close Next Set Res = Nothing CLOBRead = strReturn End Function strQry = "SELECT DBMS_LOB.GETLENGTH(contents) CONTENT_LENGTH FROM NOTICE WHERE seq=4" Rs.Open strQry, Con, 3 content = CLOBRead(Rs.Fields("CONTENT_LENGTH"), 4) %> <%=content%> <% Set Rs = Nothing Con.Close 27 Development and Operation Better Technology, Better Tomorrow Set Con = Nothing %> 9.3. VBScript Sample Source (SELECT) Dim conn, rs, sql Set conn= CreateObject("ADODB.Connection") conn.Open"Provider=tbprov.Tbprov.1;Data Source=tibero; User ID=sys;Password=tibero;" conn.CursorLocation= adUseClient 'adUseServer= 2, adUseClient= 3 Set rs= CreateObject("ADODB.RecordSet") sql= "select sysdate from dual" rs.Opensql, conn While Not rs.EOF WScript.Echors("sysdate") rs.MoveNext Wend rs.Close() Set rs= Nothing Set conn= Nothing 9.4. C# Sample Source (SELECT) //Copyright (C) Microsoft Corporation. All rights reserved. // OleDbSample.cs // To build this sample from the command line, use the command: // csc oledbsample.cs using using using using System; System.Data; System.Data.OleDb; System.Xml.Serialization; public class MainClass { public static void Main () { string strAccessConn = "Provider=tbprov.Tbprov.1; Data Source=tibero;User ID=sys;Password=tibero"; Console.WriteLine("Connection....."); string strAccessSelect = "SELECT * FROM test3"; // Create the dataset and add the Categories table to it: DataSet myDataSet = new DataSet(); OleDbConnection myAccessConn = null; try { myAccessConn = new OleDbConnection(strAccessConn); } catch(Exception ex) { Console.WriteLine("Error: Failed to create a database 28 Development and Operation Better Technology, Better Tomorrow connection. \n{0}", ex.Message); return; } try { OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect,myAccessConn); OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand); myAccessConn.Open(); myDataAdapter.Fill(myDataSet,"test3"); } catch (Exception ex) { Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message); return; } finally { myAccessConn.Close(); } // A dataset can contain multiple tables, so let's get them all // into an array: DataTableCollection dta = myDataSet.Tables; foreach (DataTable dt in dta) { Console.WriteLine("Found data table {0}", dt.TableName); } // The next two lines show two different ways you can get the // count of tables in a dataset: Console.WriteLine("{0} tables in data set", myDataSet.Tables.Count); Console.WriteLine("{0} tables in data set", dta.Count); // The next several lines show how to get information on a // specific table by name from the dataset: Console.WriteLine("{0} rows in Categories table", myDataSet.Tables["test3"].Rows.Count); // The column info is automatically fetched from the database, so // we can read it here: Console.WriteLine("{0} columns in Categories table", myDataSet.Tables["test3"].Columns.Count); DataColumnCollection drc = myDataSet.Tables["test3"].Columns; int i = 0; foreach (DataColumn dc in drc) { // Print the column subscript, then the column's name and its // data type: Console.WriteLine("Column name[{0}] is {1}, of type {2}",i++ , dc.ColumnName, dc.DataType); } DataRowCollection dra = myDataSet.Tables["test3"].Rows; foreach (DataRow dr in dra) { // Print the CategoryID as a subscript, then the CategoryName: Console.WriteLine("CategoryName[{0}] is {1}", dr[0], dr[1]); } } } 29 Development and Operation Better Technology, Better Tomorrow 9.5. C# Sample Source 2 (Retrieving a data column name) using System; using System.Data; using System.Data.OleDb; class TableAnalysis { static void Main(string[] args) { //data source=name string sql = "Provider=tbprov.Tbprov.1;User ID=tibero;Password=tmax; Data Source=tibero;Persist Security Info=True"; //location=ip,port //string sql = "Provider=tbprov.Tbprov;Password=tmax; User ID=tibero;Location=127.0.0.1,8629;Persist Security Info=True"; OleDbConnection conn = new OleDbConnection(sql); try { conn.Open(); //Connect to database OleDbCommand cmd = new OleDbCommand(); cmd.CommandText = "select * from all_tables"; // Table cmd.CommandType = CommandType.Text; //Search query cmd.Connection = conn; //select * from all_tables Result OleDbDataReader read = cmd.ExecuteReader(); Console.WriteLine("***** ALL_TABLES *****"); for (int i = 0; i < read.FieldCount; i++) { Console.WriteLine("Field Name : {0} \n", read.GetName(i)); } Console.WriteLine("Total number of fields" + read.FieldCount); read.Close(); } catch (Exception ex) { Console.WriteLine("Error{0}", ex.Message); } finally { if (conn != null) { conn.Close(); //Disconnect from database Console.WriteLine("Database disconnected.."); } } } } 9.6. ASP.NET WITH C# [Web.config] <?xml version="1.0"?> <configuration> <!—Previous Method--> <appSettings> <add key="ConnectionString" value="Provider=tbprov.Tbprov;User ID=tibero;Password=tmax;Location=127.0.0.1,8629;Persist Security Info=True"/> 30 Development and Operation Better Technology, Better Tomorrow <add key="ConnectionString2" value="Provider=tbprov.Tbprov;User ID=tibero;Password=tmax;Data Source=tibero;Persist Security Info=True"/> </appSettings> <!—Current Method--> <connectionStrings> <add name="oracle_con" connectionString="Data Source=CENT64_JP2;Persist Security Info=True;User ID=scott;Password=tiger" providerName="System.Data.OracleClient" /> <add name="tibero5_odbc" connectionString="DRIVER={Tibero 5 ODBC Driver};SERVER=127.0.0.1;PORT=8629;DB=tibero;UID=tibero;PWD=tmax" providerName="System.Data.Odbc" /> <add name="tibero5_oledb" connectionString="Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> <add name="tibero5_oledblocation" connectionString="Provider=tbprov.Tbprov.1;Location=127.0.0.1,8629;User ID=tibero;Password=tmax;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> </connectionStrings> <system.web> <compilation defaultLanguage="c#" debug="true" targetFramework="4.0"/> <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/> <globalization requestEncoding="utf-8" responseEncoding="utf-8"/> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/> <xhtmlConformance mode="Legacy"/> </system.web> </configuration> [WebForm1.aspx] <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Tutorial1.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"/> <meta name="CODE_LANGUAGE" content="C#"/> <meta name="vs_defaultClientScript" content="JavaScript"/> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"/> </head> <body> <form id="Form1" method="post" runat="server"> <asp:DataGrid id="myDataGrid" style="Z-INDEX: 101; LEFT: 136px; POSITION: absolute; TOP: 176px" runat="server" BorderColor="Tan" BorderWidth="1px" BackColor="LightGoldenrodYellow" CellPadding="2" GridLines="None" ForeColor="Black"> <SelectedItemStyle ForeColor="GhostWhite" BackColor="DarkSlateBlue"></SelectedItemStyle> <AlternatingItemStyle BackColor="PaleGoldenrod"></AlternatingItemStyle> <headerStyle Font-Bold="True" BackColor="Tan"></headerStyle> <FooterStyle BackColor="Tan"></FooterStyle> <PagerStyle HorizontalAlign="Center" ForeColor="DarkSlateBlue" BackColor="PaleGoldenrod"> </PagerStyle> </asp:DataGrid> 31 Development and Operation Better Technology, Better Tomorrow </form> </body> </html> [WebForm1.aspx.cs] using using using using System; System.Collections; System.ComponentModel; System.Data; using using using using using using using using System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient; System.Data.OleDb; namespace Tutorial { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.DataGrid myDataGrid; private void callNormalOleDbCall() { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["tibero5_oledb"].Connecti onString; string providername = System.Configuration.ConfigurationManager.ConnectionStrings["tibero5_oledb"].Provider Name; /* * Previous method to retrieve connection string information. * web.config <appSettings> <add key="ConnectionString" value="Provider=tbprov.Tbprov;User ID=tibero;Password=tmax;Location=127.0.0.1,8629;Persist Security Info=True"/> <add key="ConnectionString2" value="Provider=tbprov.Tbprov;User ID=tibero;Password=tmax;Data Source=tibero;Persist Security Info=True"/> </appSettings> */ //string connectionString = (string)System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]; Response.Write(connectionString + "<br />"); // Display /* * Currently recommended method to retrieve connection sting information. * web.config <connectionStrings> <add name="oracle_con" connectionString="Data Source=CENT64_JP2;Persist Security Info=True;User ID=scott;Password=tiger" providerName="System.Data.OracleClient" /> <add name="tibero5_odbc" connectionString="DRIVER={Tibero 5 ODBC Driver};SERVER=127.0.0.1;PORT=8629;DB=tibero;UID=tibero;PWD=tmax" 32 Development and Operation Better Technology, Better Tomorrow providerName="System.Data.Odbc" /> <add name="tibero5_oledb" connectionString="Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> </connectionStrings> */ if (String.Compare(providername, "System.Data.OleDb", true) == 0) { System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection(connectionString); System.Data.OleDb.OleDbDataReader reader = null; System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand("select sysdate from dual", myConnection); myCommand.CommandType = CommandType.Text; try { myConnection.Open(); reader = myCommand.ExecuteReader(); myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { // Catches and logs the exception } finally { reader.Close(); myConnection.Close(); } } else if (String.Compare(providername, "System.Data.Odbc", true) == 0) { //System.Data.Odbc System.Data.Odbc.OdbcConnection myConnection = new System.Data.Odbc.OdbcConnection(connectionString); System.Data.Odbc.OdbcDataReader reader = null; //Procedure call method System.Data.Odbc.OdbcCommand myCommand = new System.Data.Odbc.OdbcCommand("select sysdate from dual", myConnection); myCommand.CommandType = System.Data.CommandType.Text; try { myConnection.Open(); reader = myCommand.ExecuteReader(); myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { // Catches and logs the exception } finally { reader.Close(); myConnection.Close(); } } else { 33 Development and Operation Better Technology, Better Tomorrow System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(connectionString); System.Data.SqlClient.SqlDataReader reader = null; //Procedure call method System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("GetData", myConnection); myCommand.CommandType = System.Data.CommandType.StoredProcedure; try { myConnection.Open(); reader = myCommand.ExecuteReader(); myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { // Catches and logs the exception } finally { reader.Close(); myConnection.Close(); } } } private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack) { callNormalOleDbCall(); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } } 9.7. C# WITH Enterprise Library Enterprise Library is an open source framework provided by Microsoft. Enterprise Library is available at the following website. Microsoft Enterprise Library is a collection of reusable application blocks designed to assist software developers with common enterprise development challenges. This release includes Caching Block, Cryptography Block, Data 34 Development and Operation Better Technology, Better Tomorrow Access Block, Exception Handling Block, Logging Block, Policy Injection Block, Security Block, Validation Block, and Unity. http://msdn.microsoft.com/en-US/library/ff632023.aspx Select [Visual Studio] > [Solution Explorer] > [References] > [Add Reference]. When Enterprise Library Data Access Application Block is selected in the [Add Reference] window, data access functions can be used. [Add the following code to C#] 35 Development and Operation Better Technology, Better Tomorrow using Microsoft.Practices.EnterpriseLibrary.Data; [App.config] <?xml version="1.0"?> <configuration> <!—- The following dataConfiguration tag can only be recognized when enterpriselibrary is declared in configSections --> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" /> </configSections> <dataConfiguration defaultDatabase="tibero5_oledb" /> <connectionStrings> <add name="oracle_con" connectionString="Data Source=CENT64_JP2;Persist Security Info=True;User ID=scott;Password=tiger" providerName="System.Data.OracleClient" /> <add name="tibero5_odbc" connectionString="DRIVER={Tibero 5 ODBC Driver};SERVER=127.0.0.1;PORT=8629;DB=tibero;UID=tibero;PWD=tmax" providerName="System.Data.Odbc" /> <add name="tibero5_oledb" connectionString="Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> <add name="tibero5_oledblocation" connectionString="Provider=tbprov.Tbprov.1;Location=127.0.0.1,8629;User ID=tibero;Password=tmax;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> </connectionStrings> </configuration> [Program.cs] using System; using System.Collections.Generic; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data; using System.Data.Common; // For Oracle 36 Development and Operation Better Technology, Better Tomorrow using System.Data.OracleClient; // Exception //using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling; //using Microsoft.Practices.EnterpriseLibrary.Logging; namespace EntLibTest { class Program { static void Main(string[] args) { /* Get Connection */ Database db = conn("oracle_con"); //Database db = conn("tibero5_oledb"); //Database db = conn("tibero5_odbc"); try { //func1(db); // Tibero OLEDB OK, Tibero ODBC X //func2(db, 7934); // Tibero OLEDB X, Tibero ODBC X //func3(db, 7934); // Tibero OLEDB OK, Tibero ODBC X //func4_ora(db, 10); // Oracle func4_tbr(db, 10); // Tibero OLEDB OK, Tibero ODBC X } catch (Exception ex) { /* Display general errors */ Console.WriteLine("############# Exception !! #############"); Console.WriteLine("Message : " + ex.Message); Console.WriteLine(ex.StackTrace); /* Common error processing – Records event logs */ /* bool rethrow = ExceptionPolicy.HandleException(ex, Policy"); if (rethrow) throw; */ } } // main end static Database conn(String dbname) { //Database db = DatabaseFactory.CreateDatabase(); Database db = DatabaseFactory.CreateDatabase(dbname); Console.WriteLine("Connection : " + db.ConnectionString); return db; } // end conn /** * ( When inquiring the use of DBDataReader) ExecuteReader */ static void func1(Database db) 37 "Data Access Development and Operation Better Technology, Better Tomorrow { string sqlCommand = "select * from emp"; DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand); //StringBuilder readerData = new StringBuilder(); Console.WriteLine("#######OUTPUT(func1)######"); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { while (dataReader.Read()) { //Console.Write("{0:G}, {1:S}, {2:S} \n", dataReader["empno"], dataReader["ename"], dataReader["job"]); Console.Write("{0}, {1}, {2} \n", dataReader["empno"], dataReader["ename"], dataReader["job"]); } } } // end func1 /** * Function, return value * CREATE OR REPLACE FUNCTION get_ename ( emp_no number ) return varchar2 IS v_ename varchar2(20); BEGIN SELECT ename INTO v_ename FROM emp WHERE empno = emp_no; return v_ename; EXCEPTION WHEN NO_DATA_FOUND THEN -- ORA-01403( SQL CODE : 100 ) v_ename := 'NO_DATA_FOUND'; return v_ename; WHEN OTHERS THEN v_ename := 'OTHERS'; return v_ename; END; / * */ static void func2(Database db, int empno) { string sqlCommand = "get_ename"; DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); db.AddInParameter(dbCommand, "emp_no", DbType.VarNumeric, empno); //db.AddInParameter(dbCommand, "emp_no", DbType.Int32, empno); db.AddParameter(dbCommand, "ename", DbType.String, 20, ParameterDirection.ReturnValue, false, 0, 0, null, DataRowVersion.Default, null); db.ExecuteNonQuery(dbCommand); Console.WriteLine("#######OUTPUT(func2)######"); 38 Development and Operation Better Technology, Better Tomorrow Console.WriteLine("Ename : " + dbCommand.Parameters[1].Value); } // end func2 /** * Procedure, out parameter * CREATE OR REPLACE procedure get_ename2 ( emp_no number ,ename OUT varchar2 ,job OUT varchar2 ) IS v_ename varchar2(20); v_job varchar2(20); BEGIN SELECT ename, job INTO v_ename, v_job FROM emp WHERE empno = emp_no; ename := v_ename; job := v_job; EXCEPTION WHEN NO_DATA_FOUND THEN v_ename := 'NO_DATA_FOUND'; ename := v_ename; job := v_ename; WHEN OTHERS THEN v_ename := 'OTHERS'; ename := v_ename; job := v_ename; END; / * * */ static void func3(Database db, int empno) { string sqlCommand = "get_ename2"; DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); db.AddInParameter(dbCommand, "emp_no", DbType.VarNumeric, empno); //db.AddInParameter(dbCommand, "emp_no", DbType.Int32, empno); db.AddOutParameter(dbCommand, "ename", DbType.String, 20); db.AddOutParameter(dbCommand, "job", DbType.String, 20); db.ExecuteNonQuery(dbCommand); Console.WriteLine("#######OUTPUT(func3)######"); Console.WriteLine("Ename : " + db.GetParameterValue(dbCommand, "ename")); Console.WriteLine("job : " + db.GetParameterValue(dbCommand, "job")); } // end func3 /* * Uses SYS_REFCURSOR (for Oracle) * CRETE OR REPLACE PROCEDURE emp_list 39 Development and Operation Better Technology, Better Tomorrow ( oCursor OUT SYS_REFCURSOR , emp_no number ) IS BEGIN OPEN oCursor FOR SELECT * FROM emp WHERE empno >= emp_no ; END; / * */ static void func4_ora(Database db, int empno) { string sqlCommand = "EMP_LIST"; DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); db.AddInParameter(dbCommand, "emp_no", DbType.VarNumeric, empno); dbCommand.Parameters.Add(new OracleParameter("oCursor", OracleType.Cursor, 0, ParameterDirection.Output, true, 0, 0, String.Empty, DataRowVersion.Default, Convert.DBNull) ); Console.WriteLine("#######OUTPUT(func4_ora)######"); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { while (dataReader.Read()) { Console.Write("{0}, {1}, {2} \n", dataReader["empno"], dataReader["ename"], dataReader["job"]); } } } // end func4_ora static void func4_tbr(Database db, int empno) { string sqlCommand = "EMP_LIST"; DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); db.AddInParameter(dbCommand, "emp_no", DbType.VarNumeric, empno); //db.AddInParameter(dbCommand, "emp_no", DbType.Int32, empno); //dbCommand.Parameters.Add(new OleDbParameterTbr("oCursor", OleDbTypeTbr.Cursor, 0, ParameterDirection.Output, true, 0, 0, String.Empty, DataRowVersion.Default, Convert.DBNull)); Console.WriteLine("#######OUTPUT(func4_tbr)######"); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { while (dataReader.Read()) { Console.Write("{0}, {1}, {2} \n", dataReader["empno"], dataReader["ename"], dataReader["job"]); } } } // end func4_tbr } } 40 Development and Operation Better Technology, Better Tomorrow 9.8. C# Named Parameter Sample using using using using using using System; System.Data; System.Data.Common; System.Data.OleDb; System.Data.SqlClient; Tibero.DbAccess; class Test { static void Main(string[] args) { string connstr = "Provider=tbprov.Tbprov; Data Source=tibero; User ID=tibero; Password=tmax; Updatable Cursor=True;"; try { OleDbConnectionTbr conn = new OleDbConnectionTbr(connstr); OleDbDataAdapterTbr oda = new OleDbDataAdapterTbr(); conn.Open(); OleDbCommandTbr selectCmd = new OleDbCommandTbr(); selectCmd.Connection = conn; string query = "SELECT GOODSCODE, SUM(GOODSCNT) GOODSCNT FROM TBL_CART WHERE MEMBERID=:MEMBERID " + " AND GOODSCODE IN " + " (SELECT GOODSCODE FROM " + " (SELECT GOODSCODE, COUNT(GOODSCODE) FROM CARTSEQ=:CARTSEQ GROUP BY GOODSCODE HAVING COUNT(GOODSCODE)>1)) " + " GROUP BY GOODSCODE"; TBL_CART WHERE selectCmd.CommandText = query; selectCmd.Parameters.Add("CARTSEQ", 3); selectCmd.Parameters.Add("MEMBERID", "JCHEON"); DataSet SelectData = new DataSet(); oda.SelectCommand = selectCmd; oda.Fill(SelectData, "TBL_CART"); Console.WriteLine("=======Result[TBL_CART]========="); Console.WriteLine(SelectData.Tables["TBL_CART"].Rows[0]["GOODSCODE"].ToString()); Console.WriteLine(SelectData.Tables["TBL_CART"].Rows[0]["GOODSCNT"].ToString()); Console.WriteLine("====== end =====\n"); conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } 41 Development and Operation Better Technology, Better Tomorrow 9.9. Decompiling C# (ildasm) If ildsam is entered in [Start] > [All Programs] > [Visual Studio 2010] > [Visual Studio Tools] > [Visual Studio Command Prompt], a GUI tool appears. When the dll file (e.g., Tibero.DbAccess.dll) is selected from the file menu, the following screen appears. The method and type definition can be checked. 9.10. C# (Procedure returns cursor-SYS_REFCURSOR) CREATE OR REPLACE PACKAGE pkg003 IS PROCEDURE get_forms(curs out SYS_REFCURSOR); END; CREATE OR REPLACE PACKAGE BODY pkg003 IS -- procedure implementation PROCEDURE get_forms(curs out SYS_REFCURSOR) IS BEGIN open curs FOR select sysdate FROM dual; END; END; string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["tibero5_oledb"].Connecti onString; OleDbConnectionTbr myConnection = new OleDbConnectionTbr(connectionString); DataTable dt = new DataTable(); System.Data.OleDb.OleDbDataReader reader = null; try{ myConnection.Open(); OleDbCommandTbr cmd = new OleDbCommandTbr(); 42 Development and Operation Better Technology, Better Tomorrow cmd.Connection = myConnection; cmd.CommandText = "pkg003.get_forms"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("curs", OleDbTypeTbr.Cursor).Direction ParameterDirection.Output; reader = cmd.ExecuteReader(); myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { } finally { reader.Close(); myConnection.Close(); } 9.11. C# (Procedure returns cursor - REF CURSOR) CREATE OR REPLACE PACKAGE pkg003 IS TYPE cur004 IS REF CURSOR; PROCEDURE get_forms(curs out cur004); END; create or replace package body pkg003 is procedure get_forms(curs out cur004) is begin open curs for select sysdate from dual; end; end; create or replace procedure get_forms ( curs in out pkg003.cur004 ) is begin pkg003.get_forms(curs); end; using using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient; System.Data.OleDb; System.Data.Common; Tibero.DbAccess; namespace Tutorial 43 = Development and Operation Better Technology, Better Tomorrow { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.DataGrid myDataGrid; private void callNormalOleDbCall() { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["tibero5_oledb"].Connecti onString; string providername = System.Configuration.ConfigurationManager.ConnectionStrings["tibero5_oledb"].Provider Name; Response.Write(connectionString + "<br />"); // Display /* * Currently recommended method to retrieve connection string information. * web.config <connectionStrings> <add name="oracle_con" connectionString="Data Source=CENT64_JP2;Persist Security Info=True;User ID=scott;Password=tiger" providerName="System.Data.OracleClient" /> <add name="tibero5_odbc" connectionString="DRIVER={Tibero 5 ODBC Driver};SERVER=127.0.0.1;PORT=8629;DB=tibero;UID=tibero;PWD=tmax" providerName="System.Data.Odbc" /> <add name="tibero5_oledb" connectionString="Provider=tbprov.Tbprov.1;Data Source=tibero;User ID=tibero;Password=tmax;Pooling=True;Max Pool Size=50;Min Pool Size=2;Connection Lifetime=0" providerName="System.Data.OleDb" /> </connectionStrings> */ if (String.Compare(providername, "System.Data.OleDb", true) == 0) { OleDbConnectionTbr OleDbConnectionTbr(connectionString); myConnection DataTable dt = new DataTable(); System.Data.OleDb.OleDbDataReader reader = null; try{ myConnection.Open(); OleDbCommandTbr cmd = new OleDbCommandTbr(); cmd.Connection = myConnection; /* * CREATE OR REPLACE PACKAGE pkg003 IS TYPE cur004 IS REF CURSOR; PROCEDURE get_forms(curs out cur004); END; create or replace package body pkg003 is procedure get_forms(curs out cur004) is 44 = new Development and Operation Better Technology, Better Tomorrow begin open curs for select sysdate from dual; end; end; * * create or replace procedure get_forms ( curs in out pkg003.cur004 ) is begin pkg003.get_forms(curs); end; * */ cmd.CommandText = "get_forms"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("curs", OleDbTypeTbr.Cursor).Direction ParameterDirection.Output; reader = cmd.ExecuteReader(); Response.Write("CURSOR TEST<br />"); // Display myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { // Catches and logs the exception } finally { reader.Close(); myConnection.Close(); } } else if (String.Compare(providername, "System.Data.Odbc", true) == 0) { //System.Data.Odbc System.Data.Odbc.OdbcConnection myConnection = new System.Data.Odbc.OdbcConnection(connectionString); System.Data.Odbc.OdbcDataReader reader = null; //Method to call a procedure System.Data.Odbc.OdbcCommand myCommand = new System.Data.Odbc.OdbcCommand("select * from myConnection); myCommand.CommandType = System.Data.CommandType.Text; try { myConnection.Open(); reader = myCommand.ExecuteReader(); myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { // Catches and logs the exception } finally { reader.Close(); myConnection.Close(); } } else 45 = all_tables", Development and Operation Better Technology, Better Tomorrow { System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(connectionString); System.Data.SqlClient.SqlDataReader reader = null; // Method to call a procedure System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("GetData", myConnection); myCommand.CommandType = System.Data.CommandType.StoredProcedure; try { myConnection.Open(); reader = myCommand.ExecuteReader(); myDataGrid.DataSource = reader; myDataGrid.DataBind(); } catch (Exception) { // Catches and logs the exception } finally { reader.Close(); myConnection.Close(); } } } private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack) { callNormalOleDbCall(); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } } 9.12. ASP (BLOB Insert Sample) [Table] CREATE TABLE SPACEMAN.NOTICE3 ( SEQ NUMBER, CONTENTS BLOB 46 Development and Operation Better Technology, Better Tomorrow ); [ASP Source] <% Function ReadByteArray(strFileName) Const adTypeBinary = 1 Dim bin Set bin = CreateObject("ADODB.Stream") bin.Type = adTypeBinary bin.Open bin.LoadFromFile strFileName ReadByteArray = bin.Read End Function Set objConn = server.CreateObject("ADODB.Connection") Set cm = Server.Createobject("ADODB.Command") objConn.Open "Provider=tbprov.Tbprov;Data ID=tibero;Password=tmax;" Source=tibero;User strQry = "INSERT INTO NOTICE3 (SEQ, CONTENTS) VALUES (?, ?)" response.Write("strQry : " & strQry & "<br>") Dim seq 'The seq file value to be entered into the ‘notice 3’ table. seq=44 cm.ActiveConnection = objConn cm.CommandText = strQry cm.Parameters.Append cm.CreateParameter("@SEQ", 3, 1, Len(seq), seq) Dim fileURI fileURI = "D:\tibero\binary\tibero5-bin-5.0-windows64-69860-opt-tested.tar.gz" 'ReadByteArray(Absolute path to the file) cm.Parameters.Append cm.CreateParameter("@CONTENTS", 1,LenB(ReadByteArray(fileURI)) ,ReadByteArray(fileURI)) 'cm.CommandType = 1 <<= Cannot use cm.Execute Set cmd = Nothing objConn2.Close Set objConn2 = Nothing %> 47 205, Development and Operation Better Technology, Better Tomorrow Copyright © 2014 TmaxData Co., Ltd. All Rights Reserved. Russia Tmax Russia L.L.C. Grand Setun Plaza, No A204 Gorbunova st.2, Moscow, 121596 Tel: +7(495)970-01-35 Email: [email protected] Web (Russian): http://ru.tmaxsoft.com Trademarks Tibero RDBMS® is a registered trademark of TmaxData Co., Ltd. Other products, titles or services may be registered trademarks of their respective companies. Contact Information TmaxData can be contacted at the following addresses to arrange for a consulting team to visit your company and discuss your options. Singapore Tmax Singapore Pte. Ltd. 430 Lorong 6, Toa Payoh #10-02, OrangeTee Building. Singapore 319402 Tel: +65-6259-7223 Email: [email protected] Korea TmaxData Co., Ltd 5, Hwangsaeul-ro 329beon-gil, Bundang-gu, Seongnam-si, Gyeonggi-do. South Korea Tel: +82-31-779-7113 Fax: +82-31-779-7119 Email: [email protected] Web (Korean): http://www.tmaxdata.com Technical Support: http://technet.tmaxsoft.com United Kingdom TmaxSoft UK Ltd. Surrey House, Suite 221, 34 Eden Street, Kingston-UponThames, KT1 1ER United Kingdom Tel: + 44-(0)20-8481-3776 Email: [email protected] Web (English): http:/www.tmaxsoft.com USA TmaxSoft, Inc. 560 Sylvan Avenue Englewood Cliffs, NJ 07632. U.S.A Tel: +1-201-567-8266 Fax: +1-201-567-7339 Email: [email protected] Web (English): http://www.tmaxsoft.com Japan TmaxSoft Japan Co., Ltd. 5F Sanko Bldg, 3-12-16 Mita, Minato-Ku, Tokyo, 1080073 Japan Tel: +81-3-5765-2550 Fax: +81-3-5765-2567 Email: [email protected] Web (Japanese): http://www.tmaxsoft.co.jp China TmaxSoft China Co., Ltd. Beijing Silver Tower, RM 1508, 2 North Rd Dong San Huan, Chaoyang District, Beijing, China, 100027. China Tel: +86-10-6410-6145~8 Fax: +86-10-6410-6144 Email: [email protected] Web (Chinese): http://www.tmaxsoft.com.cn Brazil TmaxSoft Brazil Avenida Copacabana, 177 - 3 andar 18 do Forte Empresarial, Alphaville - Barueri, Sao Paulo, SP-Brasil CEP 06472-001 Email: [email protected] TD-TR3P-D0516101 48
Similar documents
Kosher Supervision - Food Service Enablers
KF04XS9HJ3R KFHMIFRJART KFR42IR41OC KFFBUWTB1G5 KFKWMAW81QE KFU4C57JOAK
More information2008 Evolution Series
Cabinet assy. E1 (csf corner cabinet) ................. 26 Cabinet assy. E2, E3 (csr seat/cabinet) .............. 28 Cabinet assy. "rsr galley cab." E2 ....................... 24 Cabinet/Hutch assy...
More information