topic
stringlengths
1
63
text
stringlengths
1
577k
ADO & SQL INSERT Statement
[quote="Baxajaun":24fy610s]Hi Avista, i've tried in my sqlite installation the following code [code=fw:24fy610s]<div class="fw" id="{CB}" style="font-family: monospace;">insert into test  <span style="color: #000000;">&#40;</span>campo1,campo2<span style="color: #000000;">&#41;</span>  values <span style="color: #000000;">&#40;</span><span style="color: #ff0000;">'1'</span>,<span style="color: #ff0000;">'texto1'</span><span style="color: #000000;">&#41;</span>,<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">'2'</span>,<span style="color: #ff0000;">'texto2'</span><span style="color: #000000;">&#41;</span></div>[/code:24fy610s] and no error. My table test structure: campo1 numeric campo2 text Can you put here your error ? Best regards[/quote:24fy610s] Many servers support multiple row inserts this way or similar way. (Note: FW_AdoImportFromDBF() uses the syntax appropriate for different servers using multiple row insert statements) Informix does not support. We need to do single row inserts only. Parameterized queries as suggested above will improve the speeds.
ADO & SQL INSERT Statement
Thanks to all for reply [quote:kqhmii31]INSERT INTO <table> SELECT <rows,static data,...> FROM <table> WHERE <cond>[/quote:kqhmii31] This is not problem but problem is to INSERT data from .TXT or .DBF file. [quote:kqhmii31]i've tried in my sqlite installation the following code CODE: SELECT ALL EXPAND VIEW insert into test (campo1,campo2) values ('1','texto1'),('2','texto2') and no error.[/quote:kqhmii31] But like Rao said, [quote:kqhmii31]Informix does not support. We need to do single row inserts only.[/quote:kqhmii31] Statements UNLOAD TO and LOAD FROM are not standard SQL statements and they are part only in IMB DbAccess I fond this on IBM info center [quote:kqhmii31]IBM Informix ODBC Driver Programmer's Manual Inserting Multiple Rows Use an insert cursor to efficiently insert rows into a table in bulk. To create an insert cursor, set the SQL_ENABLE_INSERT_CURSOR attribute using SQLSetStmtOption, then call SQLParamOptions with the number of rows as a parameter. You can create an insert cursor for data types VARCHAR, LVARCHAR, and opaque. When you open an insert cursor, a buffer is created in memory to hold a block of rows. The buffer receives rows of data as the program produces them; then they are passed to the database server in a block when the buffer is full. The buffer reduces the amount of communication between the program and the database server. As a result, the insertions go faster.[/quote:kqhmii31] Probably i need to find more informations how to CREATE INSERT CURSOR and use it. If someone have experience with this please share [b:kqhmii31]May be not bad idea FiveWin team to implement using of INSERT CURSOR[/b:kqhmii31] Thanks to all, Best regards,
ADO & SQL INSERT Statement
This is a very useful information. This can be improved upon. Also every provider provides a way to bulk import from text data. That's the fastest way. You may also check on this.
ADO & SQL INSERT Statement
Rao, I found this how to use INSERT CURSOR but still not have idea how to implement in program ... i will try this days and please if you have some experiance with this tell me some sugestions [quote:2xw5ah35] IBM Informix Guide to SQL: Tutorial Using an Insert Cursor The DECLARE CURSOR statement has many variations. Most are used to create cursors for different kinds of scans over data, but one variation creates a special kind of cursor, called an insert cursor. You use an insert cursor with the PUT and FLUSH statements to efficiently insert rows into a table in bulk. Declaring an Insert Cursor To create an insert cursor, declare a cursor to be for an INSERT statement instead of a SELECT statement. You cannot use such a cursor to fetch rows of data; you can use it only to insert them. The following 4GL code fragment shows the declaration of an insert cursor: DEFINE the_company LIKE customer.company, the_fname LIKE customer.fname, the_lname LIKE customer.lname DECLARE new_custs CURSOR FOR INSERT INTO customer (company, fname, lname) VALUES (the_company, the_fname, the_lname) When you open an insert cursor, a buffer is created in memory to hold a block of rows. The buffer receives rows of data as the program produces them; then they are passed to the database server in a block when the buffer is full. The buffer reduces the amount of communication between the program and the database server, and it lets the database server insert the rows with less difficulty. As a result, the insertions go faster. The buffer is always made large enough to hold at least two rows of inserted values. It is large enough to hold more than two rows when the rows are shorter than the minimum buffer size. Inserting with a Cursor The code in the previous example prepares an insert cursor for use. The continuation, as the following example shows, demonstrates how the cursor can be used. For simplicity, this example assumes that a function named next_cust returns either information about a new customer or null data to signal the end of input. EXEC SQL BEGIN WORK; EXEC SQL OPEN new_custs; while(SQLCODE == 0) { next_cust(); if(the_company == NULL) break; EXEC SQL PUT new_custs; } if(SQLCODE == 0) /* if no problem with PUT */ { EXEC SQL FLUSH new_custs; /* write any rows left */ if(SQLCODE == 0) /* if no problem with FLUSH */ EXEC SQL COMMIT WORK; /* commit changes */ } else EXEC SQL ROLLBACK WORK; /* else undo changes */ The code in this example calls next_cust repeatedly. When it returns non-null data, the PUT statement sends the returned data to the row buffer. When the buffer fills, the rows it contains are automatically sent to the database server. The loop normally ends when next_cust has no more data to return. Then the FLUSH statement writes any rows that remain in the buffer, after which the transaction terminates. Re-examine the INSERT statement on page ***. The statement by itself, not part of a cursor definition, inserts a single row into the customer table. In fact, the whole apparatus of the insert cursor can be dropped from the example code, and the INSERT statement can be written into the code where the PUT statement now stands. The difference is that an insert cursor causes a program to run somewhat faster. Status Codes After PUT and FLUSH When a program executes a PUT statement, the program should test whether the row is placed in the buffer successfully. If the new row fits in the buffer, the only action of PUT is to copy the row to the buffer. No errors can occur in this case. However, if the row does not fit, the entire buffer load is passed to the database server for insertion, and an error can occur. The values returned into the SQL Communications Area (SQLCA) give the program the information it needs to sort out each case. SQLCODE and SQLSTATE are set to zero after every PUT statement if no error occurs and to a negative error code if an error occurs. The database server sets the third element of SQLERRD to the number of rows actually inserted into the table, as follows: Zero, if the new row is merely moved to the buffer The number of rows that are in the buffer, if the buffer load is inserted without error The number of rows inserted before an error occurs, if one did occur Read the code once again to see how SQLCODE is used (see the previous example). First, if the OPEN statement yields an error, the loop is not executed because the WHILE condition fails, the FLUSH operation is not performed, and the transaction rolls back. Second, if the PUT statement returns an error, the loop ends because of the WHILE condition, the FLUSH operation is not performed, and the transaction rolls back. This condition can occur only if the loop generates enough rows to fill the buffer at least once; otherwise, the PUT statement cannot generate an error. The program might end the loop with rows still in the buffer, possibly without inserting any rows. At this point, the SQL status is zero, and the FLUSH operation occurs. If the FLUSH operation produces an error code, the transaction rolls back. Only when all inserts are successfully performed is the transaction committed.[/quote:2xw5ah35] [b:2xw5ah35]May be not bad idea FiveWin team to implement using of INSERT CURSOR[/b:2xw5ah35] Best regards,
ADO + FWH + DBF + SQL
Buenas a todos, 1) De donde puedo sacar información de las propiedades y metodos de ADO?? 2) Quisiera saber que estoy haciendo mal en este código. El Browse con el primer recordset me lo muestra de maravilla, ahora cuando quiero insertar en la tabla F10TAA.DBF el contenido de F10T01 (Las dos son iguales) me da el siguiente error. Error occurred at: 11/08/06, 04:14:32 Error description: Error ADODB.RecordSet/14 DISP_E_BADPARAMCOUNT: EXECUTE Args: Stack Calls =========== Called from: win32ole.prg => TOLEAUTO:EXECUTE(0) Called from: TestAdo.prg => MAIN(105) El código más abajo. FUNCTION MAIN() LOCAL oRs, oRs1, cConn , cConn1 , oErr ,cSQL, cSQL1, cSQL_select, cSQL_from, cSQL_where, cSQL_order cSQL_select = "select F10T01.CODINTPRD, F10T01.NOMPRD, F10T01.PRCSUG, F10T01.CODRUB, F10G02.NOMRUB, F10T01.CODBAR " cSQL_from = "from F10T01, F10G02 " cSQL_where = "where F10T01.CODRUB = F10G02.CODRUB and F10T01.CODBAR = '8888888888888'" cSQL_order = "order by F10T01.NOMPRD" cSQL = cSQL_select + cSQL_from + cSQL_where + cSQL_order oRs := CreateObject("ADODB.RecordSet") oRs:CursorLocation := adUseClient oRs:LockType := adLockOptimistic oRs:CursorType := adOpenDynamic oRs:ActiveConnection := "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\ft\apl;Extended Properties=dBASE IV" oRs:Source := cSQL TRY oRs:Open() oRs:MoveFirst() CATCH oErr ? oErr:Description RETURN NIL END TRY // Funciona OK!!!! TCBROWSERECORDSET( oRs ) oRs:Close() oRs := CreateObject("ADODB.RecordSet") oRs:CursorLocation := adUseClient oRs:LockType := adLockOptimistic oRs:CursorType := adOpenDynamic oRs:ActiveConnection := "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\ft\apl;Extended Properties=dBASE IV" oRs:Source := cSQL1 // Aquí es donde da el error cSQL1 = "insert into F10TAA ( CODINTPRD, NOMPRD, PRCVTA, PRCSUG, CODBAR ) select CODINTPRD, NOMPRD, PRCVTA, PRCSUG, CODBAR from F10T01 where CODBAR = '8888888888888'" oRs:Open() oRs:Update() oRs:Close() RETURN NIL --------------------------------------------------------------------------------- Muchas Gracias a todos, Ariel S Gigliotti
ADO + FWH + DBF + SQL
Ariel Me invadió la duda.... pero prueba a colocar la declaración de la consulta cSQL1 antes de asignarle a oRs:Source cSQL1 = "insert into F10TAA ( CODINTPRD, NOMPRD, PRCVTA, PRCSUG, CODBAR ) select CODINTPRD, NOMPRD, PRCVTA, PRCSUG, CODBAR from F10T01 where CODBAR = '8888888888888'" oRs:Source := cSQL1 Puedes enontrar más información de los objetos ADO en [url:qyipp1g4]http&#58;//msdn&#46;microsoft&#46;com/library/default&#46;asp?url=/library/en-us/ado270/htm/mdobjfield&#46;asp[/url:qyipp1g4] Marcelo Jingo
ADO + FWH + DBF + SQL
Segun mi conocimiento de ADO no deberias de modificar o insertar datos usando un query, ADO tiene metodos para hacer eso directamente. Si quieres por ejemplo modificar un dato del record set haces: oRs:field(x):Value := lo que quieras oRs:Update() si haces un query que inserte datos en una tabla o que los modfique el resultado de la ejecucion de dicho query, sobre un recordset, lo que este recordset te devuelve NO ES LA TABLA CON EL REGISTRO ACTUALIZADO O MODIFICADO, el recorset regresa el resultado de la operacion realizada, puede ser un valor numerico, o un valor logico, pero nunca regresa una tabla.
ADO + FWH + DBF + SQL
Gracias por la ayuda, me podrían decir como veo los metodos y propiedades para trabajar con ADO en FHW?, Gracias. Ariel,
ADO + FWH + DBF + SQL
El siguiente link puede serte de gran ayuda [url:1n99odyj]http&#58;//www&#46;aspfacil&#46;com/articulos/040401&#46;asp[/url:1n99odyj] Un saludo Marcelo Jingo
ADO + FWH + DBF + SQL
Amiguinho Ustedes podes visualizar en: [url=http&#58;//ns7&#46;webmasters&#46;com/caspdoc/html/ado_component_reference&#46;htm:1x31ap2r]SunChilliSoft.ASP[/url:1x31ap2r] És mui simples usar ADO con Fivewin.
ADO + FWH + SQL SERVER
Hola, Una pregunta levanto un recordset con Ado usando la libreria de jlcapel y dependiendo la cantidad de campos que me retorne en el SELECT me da el error hb_xgrab(0) not allocate memory y tal vez son 20 campos, a alguien le paso ? y lo pudo solucionar. Gracias.
ADO + MS-SQL
Foro buenos días, estoy probando ADO + MS-SQL y va muy bien, pero me he topado con un problema. Estoy haciento una consulta la cual me regresa un oRS con tres campos uno de tipo TinyInt y dos de tipo nVarChar pero recorrer el oRs para meter los datos en un Array este me marca este error "OLE Error Value : Unknown error", esto cuando intento tomar el valor con : nEmpresa:=oRs:Fields('InEmpNum'):Value InEmpNum es del tipo TinyInt, pero si cambio este campo a tipo Int el error ya no se presenta Tengo que definir algo ? De antemano mil gracias Joel Andujo
ADO + MS-SQL
Los campos TinyInt se utilizan para los campos lógicos ( .T. o .F. )
ADO + MS-SQL
Gracias Zamoras, lo curioso es es que pruebo con un campo tipo SmallInt y sucede lo mismo, no reconoce el tipo de dato. al leerlo con nEmpresa:=oRs:Fields('InEmpNum'):Value me marca "OLE Error Value : Unknown error" Al pareder la clase no reconoce los campos tipo Tinyint e SmallInt y ale busque y la verdad no se por donde van los tiros, alguien que ya este trabajando con OleDB, hechem un cable por favor. Hay una versión mas actualizada de la clase Ole del Maestro Jóse Gimenez ? Saludo Joel Andujo
ADO + MS-SQL
Yo lo hago de la siguiente forma: [code:sb3re2eh] &#58;&#58;TipoCampo&#40; oQuery&#58;Get&#40; "Type" &#41; &#41; ////// //------------------------------------------------------------------------------------// METHOD TipoCampo&#40; &#41; retorna el tipo de campo&#46; //------------------------------------------------------------------------------------ METHOD TipoCampo&#40; nTipo &#41; CLASS TConexion SWITCH nTipo //DO CASE CASE 202; CASE 130; CASE 200; CASE 129 // Carácter&#46; RETURN "C" CASE 14; CASE 5; CASE 3; CASE 131; CASE 2; CASE 4 // Numérico&#46; RETURN "N" CASE 7; CASE 133; CASE 135 // Fecha RETURN "D" CASE 11; CASE 16 // Lógico RETURN "L" CASE 203; CASE 11; CASE 128 // Campo memo RETURN "M" DEFAULT MsgInfo&#40; "Tipo de dato no válido&#58; " + STR&#40; nTipo &#41; &#41; END // SWITCH CASE RETURN NIL [/code:sb3re2eh] Espero que esto te ayude.Saludos.
ADO + MS-SQL
Acabo de revisar un ejemplo con SQL Server y con ADO y me esta regresando bien los valores. (x)Harbour 99.5 y FW 2.6
ADO + MS-SQL
Joel, [quote:3e98qt9c]"OLE Error Value : Unknown error", esto cuando intento tomar el valor con : nEmpresa:=oRs:Fields('InEmpNum'):Value [/quote:3e98qt9c] Usas ADO contra MySql... ¿Como? ¿ODBC? Si es Odbc, cual versión de MyOdbc usas?? ¿Cual versión de MySql? ¿y de ADO? Saludos, José Luis Capel
ADO + MS-SQL
José Luis, estoy usando FWH 2.4 + Microsoft-SQL + ADO (TOleAuto del master José Gimenez) Ya he trabajado con Odbc utilizando TOdbc() y va muy bien, pero ahora busco mejorar los tiempos usando ADO y me he topado con el problema que les comento. Gracias a todos saludos Joel Andujo
ADO + MS-SQL
Joel, Si es la versión original de tOleAuto (y no la que viene actualmente con xharbour) es probable (y repito probable) que ahí radique el problema. Intenta bajarte los ultimos binarios de xhabour. Y, desde xharbour (son FWH) intenta hacer las mismas operaciones. Casi te puedo asegurar que no vas a tener ningún problema. Ya me contarás como te fue. Saludos, José Luis Capel
ADO + MS-SQL
Gracias José Luis por ahi me voy a ir, de hecho tengo la inquietud desde hace algun tiempo de cambiarme a xHarbour y ahora con mas razón. Ya te contaré como me fue Saludos Joel Andujo
ADO + MS-SQL
José Luis, exacto era eso!!!, despues de pegarme un tiro(buscarle, buscarle y volver a buscrale) recompilando FW24 y mis librerias de terceros con xHarbour 0.99.50 (SimPlex) de xHarbour.org ya el ejemplo de ADO me regresa los valores correctos. Saludos Joel Andujo
ADO - Error description: Error ADODB.RecordSet/6 DIS
Tengo una duda y lo voy a ser sencillo a ver si por ahi resuelvo el quilombete. [code=fw:1d6gj5bn]<div class="fw" id="{CB}" style="font-family: monospace;"><span style="color: #00C800;">FUNCTION</span> buscar<span style="color: #000000;">&#40;</span>cBuscar, oRs, oBrw<span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;cBuscar = AllTrim<span style="color: #000000;">&#40;</span>cBuscar<span style="color: #000000;">&#41;</span><br /><br />&nbsp; &nbsp;oRs:<span style="color: #000000;">MoveFirst</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <----------- ACA ESTA MI DUDA!<br />&nbsp; &nbsp;<span style="color: #00C800;">IF</span> !Empty<span style="color: #000000;">&#40;</span>cBuscar<span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;oRs:<span style="color: #000000;">find</span><span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"nombre LIKE '%"</span>+cBuscar+<span style="color: #ff0000;">"%'"</span>,,<span style="color: #000000;">1</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">ENDIF</span><br /><br />&nbsp; &nbsp;<span style="color: #00C800;">IF</span> !<span style="color: #000000;">&#40;</span>oRs:<span style="color: #000000;">Eof</span> .or. ors:<span style="color: #000000;">Bof</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; oBrw:<span style="color: #0000ff;">refresh</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">ENDIF</span><br /><span style="color: #00C800;">RETURN</span> <span style="color: #000000;">&#40;</span><span style="color: #00C800;">nil</span><span style="color: #000000;">&#41;</span><br />&nbsp;</div>[/code:1d6gj5bn] Intuyo que el error del programa se debe a que primero lo mando al puntero al primer registro y luego lo hago buscar... no hay problema si lo encuentra. Si hay problema cuando no lo encuentra, para mi " pierde" la sincronizacion con los bookMark, al querer retornar al browser no sabe donde quedo y larga el dichoso error [quote:1d6gj5bn]Error description: Error ADODB.RecordSet/6 DISP_E_UNKNOWNNAME: BOOKMARK Args:[/quote:1d6gj5bn] es esto asi? he probado antes de hacer el movefirst() salvar el booMArk asi [code=fw:1d6gj5bn]<div class="fw" id="{CB}" style="font-family: monospace;"> <span style="color: #00C800;">LOCAL</span> bBookMarkActual:= oBrw:<span style="color: #000000;">bBookMark</span></div>[/code:1d6gj5bn] y luego restaurarlo asi: [code=fw:1d6gj5bn]<div class="fw" id="{CB}" style="font-family: monospace;"> <span style="color: #00C800;">IF</span> !<span style="color: #000000;">&#40;</span>oRs:<span style="color: #000000;">Eof</span> .or. ors:<span style="color: #000000;">Bof</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; oBrw:<span style="color: #0000ff;">refresh</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">ELSE</span><br />&nbsp; &nbsp; &nbsp; oBrw:<span style="color: #000000;">bBookMark</span>:= bBookMarkActual<br />&nbsp; &nbsp; &nbsp; oBrw:<span style="color: #0000ff;">refresh</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">ENDIF</span></div>[/code:1d6gj5bn] pero sigue el error. Que solucion puede tener esto? gracias.
ADO - Error description: Error ADODB.RecordSet/6 DIS
Siempre que hagas una búsqueda es obligatorio poner el RecodSet en el primer registro. oRs : MoveFirst() Te paso este enlace que está muy bueno <!-- m --><a class="postlink" href="http://www.w3schools.com/ado/ado_ref_recordset.asp">http://www.w3schools.com/ado/ado_ref_recordset.asp</a><!-- m --> Saludos
ADO - Error description: Error ADODB.RecordSet/6 DIS
entonces que le estoy h/errando?
ADO - SQL-question
Hi, Is is correct to say that if I download the connector <!-- m --><a class="postlink" href="http://dev.mysql.com/downloads/connector/odbc/5.1.html">http://dev.mysql.com/downloads/connector/odbc/5.1.html</a><!-- m --> and use MariaDB, I can use MySQL with xHarbour without buying any other server licence? Or do I need someting else? Thanks, Marc
ADO - SQL-question
Marc SQL Server Express is a free edition of SQL Server ideal for developing and powering desktop, web and small server applications. <!-- m --><a class="postlink" href="http://www.microsoft.com/sqlserver/en/us/editions/2012-editions/express.aspx">http://www.microsoft.com/sqlserver/en/u ... press.aspx</a><!-- m --> The beauty of using Ms Sql server is that you can use ADO SqlOleDB which is loaded on every Microsoft computer .. you will not need to download any clients or worry about configuring ODBC. Deploy your app and use it from any Windows computer nothing else is needed. Rick Lipkin
ADO - SQL-question
Marc: If you use MariaDb then you don't need MySql and viceversa, and yes !, you need the connector to use MariaDB or MySql with ADO. I have a medium size app developed with ADO, xHarbour, FW and MySql, I made a test with MariaDB and no change was necessary, all the code has been accepted. Regards
ADO - SQL-question
[quote="Rick Lipkin":2v1qg84r]Marc SQL Server Express is a free edition of SQL Server ideal for developing and powering desktop, web and small server applications. <!-- m --><a class="postlink" href="http://www.microsoft.com/sqlserver/en/us/editions/2012-editions/express.aspx">http://www.microsoft.com/sqlserver/en/u ... press.aspx</a><!-- m --> The beauty of using Ms Sql server is that you can use ADO SqlOleDB which is loaded on every Microsoft computer .. you will not need to download any clients or worry about configuring ODBC. Deploy your app and use it from any Windows computer nothing else is needed. Rick Lipkin[/quote:2v1qg84r] Rick, Thanks, for the very useful information. Do you have an example how to connect to this server? Regards, Marc
ADO - SQL-question
[quote="Armando":3pao8n30]Marc: If you use MariaDb then you don't need MySql and viceversa, and yes !, you need the connector to use MariaDB or MySql with ADO. I have a medium size app developed with ADO, xHarbour, FW and MySql, I made a test with MariaDB and no change was necessary, all the code has been accepted. Regards[/quote:3pao8n30] Armando, Thank you for the information. Is the connector a free download, or is there a limitation? I thought once to have read on this forum that this was not free. Regards, Marc
ADO - SQL-question
Marc: As I know, the connector is free but MySql is Freeware, here is the link for mariaDB, perhaps is your best option. <!-- m --><a class="postlink" href="http://mariadb.org/en/">http://mariadb.org/en/</a><!-- m --> Best regards
ADO - SQL-question
Mark Here is a very simple example how to set up the Sql Server Connection and how to open a recordset. Rick [code=fw:1urbxj2m]<div class="fw" id="{CB}" style="font-family: monospace;"><br /><br /><span style="color: #00C800;">Local</span> oRsRepair,cSql,oErr<br /><span style="color: #00C800;">Public</span> xConnect<br /><br />xPROVIDER   := <span style="color: #ff0000;">"SQLOLEDB"</span><br />xSOURCE     := <span style="color: #ff0000;">"YOURSQLSERVERNAME"</span>   <br />xCATALOG    := <span style="color: #ff0000;">"YOURDATABASENAME"</span><br />xUSERID      := <span style="color: #ff0000;">"user"</span>                       <span style="color: #B900B9;">// this username has to have permission</span><br />xPASSWORD := <span style="color: #ff0000;">"password"</span>                <span style="color: #B900B9;">// to login to the database</span><br /><br />xCONNECT := <span style="color: #ff0000;">'Provider='</span>+xPROVIDER+<span style="color: #ff0000;">';Data Source='</span>+xSOURCE+<span style="color: #ff0000;">';Initial Catalog='</span>+xCATALOG+<span style="color: #ff0000;">';User Id='</span>+xUSERID+<span style="color: #ff0000;">';Password='</span>+xPASSWORD<br /><br />cSql := <span style="color: #ff0000;">"Select * from YOURTABLE"</span><br /><br />oRsRepair := TOleAuto<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>:<span style="color: #00C800;">New</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"ADODB.Recordset"</span> <span style="color: #000000;">&#41;</span><br />oRsRepair:<span style="color: #000000;">CursorType</span>     := <span style="color: #000000;">1</span>        <span style="color: #B900B9;">// opendkeyset</span><br />oRsRepair:<span style="color: #000000;">CursorLocation</span> := <span style="color: #000000;">3</span>        <span style="color: #B900B9;">// local cache</span><br />oRsRepair:<span style="color: #000000;">LockType</span>       := <span style="color: #000000;">3</span>        <span style="color: #B900B9;">// lockoportunistic</span><br /><br /><span style="color: #00C800;">TRY</span><br />   oRsRepair:<span style="color: #000000;">Open</span><span style="color: #000000;">&#40;</span> cSQL,xCONNECT <span style="color: #000000;">&#41;</span><br />CATCH oErr<br />   <span style="color: #0000ff;">MsgInfo</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"Error in Opening REPAIR table"</span> <span style="color: #000000;">&#41;</span><br />   <span style="color: #00C800;">RETURN</span><span style="color: #000000;">&#40;</span>.F.<span style="color: #000000;">&#41;</span><br />END <span style="color: #00C800;">TRY</span><br /><br /><span style="color: #0000ff;">xbrowse</span><span style="color: #000000;">&#40;</span> oRsRepair <span style="color: #000000;">&#41;</span><br /><br />oRsRepair:<span style="color: #000000;">CLose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br /><br /> </div>[/code:1urbxj2m]
ADO - consultar el ultimo registro ingresado en una tabla.
Hola Foro: Alguien sabe como conocer cual es el valor del ultimo registro creado en un campo autonumerico de una tabla access 2000. Los campos autonumericos, son aquellos que el motor les asignan solo un valor numerico incremental, por lo general de 1 en 1. Mi problema, es que necesito conocer el valor antes de grabar el recordset, pues es un dato mas de mi registro y no se cual es el que le asignará. Alguna idea ?? Saludos [/b]
ADO - consultar el ultimo registro ingresado en una tabla.
Juan oRs:Insert_ID( ) Regresa el ultimo identificador de numeracion automatico insertado (serial). Regresa falso si la funcion no esta soportada. Un saludo Marcelo Jingo
ADO - consultar el ultimo registro ingresado en una tabla.
[b:6hl4alk4] GRACIAS[/b:6hl4alk4] Marcelo, la voy a probar. No conocia esa funcion. Saludos,
ADO -> Metodo Clone()
Hola a todos, Alguien me podria explicar para q carajos sirve hacer un ::Clone() de un oRS. Vale, ya se q hace una copia referencial del oRS, pero q ventajas aporta y para y cuando se debe usar ? Gracias.
ADO -> Metodo Clone()
Yo lo utilizo cuando estoy mostrando el recordset en un browse y quiero hacer otra operación con ese recordset. de esta manera cada recordset mantiene su posición. Esta es una, supongo que tendrá más utilidades. Saludos
ADO -> Metodo Clone()
Horacio, Si, ya he probado el tema de realizar busquedas o aplicar filtros. Realmente es mas rapido q volver a crear y ejecutar una nueva select. Entiendo que cualquier operacion que hagas es sobre el conjunto de datos seleccionados previamente con el RecordSet, o puedes realizar una nueva select ? (creo q he dicho una barbaridad...) Saludos. C.
ADO -> Metodo Clone()
Carles: Ummm, me parece que no has dicho una barbaridad, pues tambien puedes hacer un nuevo SELECT de la misma tabla aunque ya tengas uno creado. Te pongo un ejemplo donde puede aplicarse: Supongamos que ya tienes creado un record set de toda la tabla de clientes con el cual creas un browse, ahora imagina que deseas registrar un nuevo cliente, obviamente para no duplicar el cliente debes revisar que no este registrado ya, en una aplicación monousuario no habría mayor problema pues simplemente buscas en el recordset que tienes creado y listo peroooo, si es un ambiente multiusuario (que es lo más lógico) debes estar seguro que ningun otro usuario haya dado de alta el cliente que tu pretendes registrar, en este caso con buscar en el recordset no es suficiente. El problema es que el record set no se auto refresca con los nuevos registros que otro usuario adicione, debes hacerlo tú por código oRs:Refresh(), bien en un timer para que te refresque l recordset cada n tiempo o bien buscarlo en la tabla origen y eso lo harías creando un nuevo recordset seleccionando solamente el cliente que pretendes registrar, si el recordset te queda vacio significa que nadie más lo ha registrado antes que tú. Aqui estamos creando dos record sets desde una misma tabla. Ojalá me haya explicado y esto sea la respuesta a tu pregunta. Saludos
ADO -> Metodo Clone()
Armando, Gracias. He experimentado un poco y mi conclusion es: Nosotros creamos un RecordSet con seleccion de datos a gestionar. Con el :Clone(), podemos rapidamente disponer de un objeto referencia q nos permitira hacer busquedas, filtros, y manipulaciones de los datos clonados. El bookmark siempre es el mismo q el original. Podemos facilmente refrescar el clone si lo necesitamos. Y sobre el hecho de dar de altas, me parece q lo tengo mu claro. Si tengo una clave unica de codigo, manejo el gestor de errores y facilmente se si he actualizado o no. Si ya existe el registro, pues canta... [code=fw:1dacwzd2]<div class="fw" id="{CB}" style="font-family: monospace;"><br /><span style="color: #00C800;">TRY</span><br />      ::<span style="color: #000000;">oRs</span>:<span style="color: #0000ff;">Update</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br /><br />     CATCH oError<br /><br />       <span style="color: #00C800;">FOR</span> EACH oError IN oConn:<span style="color: #000000;">Errors</span><br />           TAdoError<span style="color: #000000;">&#40;</span> oError <span style="color: #000000;">&#41;</span><br />       <span style="color: #00C800;">NEXT</span><br /><br />END<br /> </div>[/code:1dacwzd2]
ADO -> Registros en un recordset
Hola, No se si digo una tonteria, pero como puedo saber los registros que hay un recordset, una vez he reallizado el :Open() ? Gracias.
ADO -> Registros en un recordset
Si la cadena es cCadenaRecordset := "Select nombre, calle, numero from clientes" una vez que obtengas el recordset lo puedes recorrer de la siguiente manera While( !oRecordSet : Eof() ) ? oRecordSet : Fields( "nombre" ) : Value, oRecordSet : Fields( "calle" ) : Value, oRecordSet : Fields( "numero" ) : Value oRecordSet : MoveNext() Enddo Espero te sirva Saludos
ADO -> Registros en un recordset
Hola Horacio, Gracias, pero yo quiero saber si existe alguna funcion, metodo, variables, ... sin tener q recorrerme todo el recordset <!-- s:D --><img src="{SMILIES_PATH}/icon_biggrin.gif" alt=":D" title="Very Happy" /><!-- s:D --> Gracias.
ADO -> Registros en un recordset
Horacio, asi : ? 'No. de Registros '+ str( oRs:Recordcount() ) Saludos Joel Andujo
ADO -> Registros en un recordset
Joel, Joder gracias !!! -> A veces un arbol no te deja ver un bosque <!-- s:mrgreen: --><img src="{SMILIES_PATH}/icon_mrgreen.gif" alt=":mrgreen:" title="Mr. Green" /><!-- s:mrgreen: --> Gracies.
ADO -ms-sql - xharb 1.0 - create database user schema?
I have to create a database in MS-Sql server automatically from my install program. Is it possible, using ADO, to issue direct native "sql-string" calls to a sql-server to create the following? - users - databases -schemas?
ADO -ms-sql - xharb 1.0 - create database user schema?
I am doing with Oracle + ADO (users + schemas)
ADO -ms-sql - xharb 1.0 - create database user schema?
Don Generally I have to get our DBA's involved to set up a database for me and set up a userid for my connection. Once that is done .. I control the application ( users ) thru tables .. Hopefully you will be given 'create' and 'drop' rights .. I have my own 2005 SQL server that I use as my development box .. and I control that and do everything I need with SQL Studio 2005. Hope that helps .. I don't think you can create a database in a schima with scripts... Rick
ADO -ms-sql - xharb 1.0 - create database user schema?
Once a database is created, we can create tables, indexes, even procedures through ADO. Both on Oracle and MSSQL. One way is by sending the create scripts as commands in execute method and another way is to use ADOX. In any case the user logged in should have create permissions. I do not know if we can create database itself though ADO.
ADO -ms-sql - xharb 1.0 - create database user schema?
It works for me on MS SQL server 2005 [code:1fsdwoe8] #INCLUDE "FIVEWIN&#46;CH" #INCLUDE "xbrowse&#46;CH" //---------------------- Function main&#40;&#41; LOCAL oRs1,oRs2,oRs3,oErr,cSQl1,cSql2, cSQL,cTitle,oBrw,oWnd msgInfo&#40;"Start"&#41; cSQL &#58;= "create database jbc" cSql1&#58;= "CREATE LOGIN jbc2 WITH PASSWORD = 'hhhh'; "; +"USE jbc; "; +"CREATE USER jbc2 FOR LOGIN jbc2 " cSQl2 &#58;= "CREATE SCHEMA jbc AUTHORIZATION jbc2 "; +"CREATE TABLE test &#40;source int, cost int, partnumber int&#41; "; +"GRANT SELECT TO jbc2 " oRs1 &#58;= TOleAuto&#40;&#41;&#58;New&#40; "ADODB&#46;Recordset" &#41; oRs1&#58;CursorType &#58;= 1 // opendkeyset oRs1&#58;CursorLocation &#58;= 3 // local cache oRs1&#58;LockType &#58;= 3 // lockoportunistic TRY oRS1&#58;Open&#40; cSql,'Provider=SQLOLEDB;Data Source=OGNEW;Initial Catalog=;User Id=sa1;Password=qqqe' &#41; CATCH oErr MsgInfo&#40; "Error in creating database" &#41; RETURN&#40;&#46;F&#46;&#41; END TRY oRs3 &#58;= TOleAuto&#40;&#41;&#58;New&#40; "ADODB&#46;Recordset" &#41; oRs3&#58;CursorType &#58;= 1 // opendkeyset oRs3&#58;CursorLocation &#58;= 3 // local cache oRs3&#58;LockType &#58;= 3 // lockoportunistic TRY oRs3&#58;Open&#40; cSql1,'Provider=SQLOLEDB;Data Source=OGNEW;Initial Catalog=;User Id=sa1;Password=qqqe' &#41; CATCH oErr MsgInfo&#40; "Error in creating user" &#41; RETURN&#40;&#46;F&#46;&#41; END TRY oRs2 &#58;= TOleAuto&#40;&#41;&#58;New&#40; "ADODB&#46;Recordset" &#41; oRs2&#58;CursorType &#58;= 1 // opendkeyset oRs2&#58;CursorLocation &#58;= 3 // local cache oRs2&#58;LockType &#58;= 3 // lockoportunistic TRY oRs2&#58;Open&#40; cSql2,'Provider=SQLOLEDB;Data Source=OGNEW;Initial Catalog=jbc;User Id=sa1;Password=qqqe' &#41; CATCH oErr MsgInfo&#40; "Error in crating table" &#41; RETURN&#40;&#46;F&#46;&#41; END TRY Return nil [/code:1fsdwoe8] That scripts generate database, user and schema regards Eugeniusz
ADO -ms-sql - xharb 1.0 - create database user schema?
Mr Eugeniusz Owsiak Thanks for the info.
ADO -ms-sql - xharb 1.0 - create database user schema?
I will try the test for creating databases provided by Mr Owsiak. This may be just what I was looking for. I would like to deliver our applications to clients with complete seamlessness for end users. Many of our end users are not very computer savy. MS-Sql server is becoming quite popular and dependable and many small businesses (banks in my case). These clients are leary of .dbf files and want the MS-Sql database. Most of these clients don't have a DBA. This is very useful for me - I want to deliver a solution as seamless as when I did it with .dbf files. I would package the sql-server engine with our distribution CD and build/maintain the databases 100% within code. Most likely, I would be the only one ever using the Visual Studio / Enterprise Manager for actual administration of the end databases. Most of my users want to be insulated from these tasks. Thanks again to all who replied.
ADO -ms-sql - xharb 1.0 - create database user schema?
Eugeniusz, I wanted to take a moment to thank you for your examples of creating a MS-SQL database, login, user, and schema. Your examples were very helpful, and your response is greatly appreciated. I did modularize the calls to allow calling each create individually. Also for flexibility, we capture the varaibles(sa password, database name, login...) via a dialog. One other modification I made is adding an execute to change the login/user to a "db_owner" as follows: MDB is the DataBase name from the dialog MLOGIN is the MS-SQL Login from the dialog cUSER is the DataBase User from the dialog LOCAL cSQLCdbu := "USE " + MDB + "; " ; +"CREATE USER "+cUSER+" FOR LOGIN "+MLOGIN+ "; " ; +"EXEC sp_addrolemember 'db_owner', '" +cUSER+"'" We certainly appreciate your assistance. Regards, Perry Nichols
ADO -ms-sql - xharb 1.0 - create database user schema?
Mr Lowenstain You can also from management studio 1. make setup of database, users, logins schemas etc 2. creating backap to file, 3. copying backap file to your didrtibution media 4.restoring database with this script&#058; [code:33j6weqd] #INCLUDE "FIVEWIN&#46;CH" //---------------------- Function main&#40;&#41; LOCAL oRs1,oErr,cSQL msgInfo&#40;"Start"&#41; cSQL&#58;="RESTORE DATABASE jbc "; +"FROM DISK = 'c&#58;\Program Files\Microsoft SQL Server\MSSQL&#46;1\MSSQL\Backup\jbc&#46;bak' " oRs1 &#58;= TOleAuto&#40;&#41;&#58;New&#40; "ADODB&#46;Recordset" &#41; oRs1&#58;CursorType &#58;= 1 // opendkeyset oRs1&#58;CursorLocation &#58;= 3 // local cache oRs1&#58;LockType &#58;= 3 // lockoportunistic TRY oRS1&#58;Open&#40; cSql,'Provider=SQLOLEDB;Data Source=OGNEW;Initial Catalog=;User Id=sa1;Password='qqqe' &#41; CATCH oErr MsgInfo&#40; "Error in restoring database" &#41; END TRY Return nil [/code:33j6weqd] This is easiest way to solve your problem regards Eugeniusz
ADO .. how to write ctod('00/00/00') to MS Sql Server
To All I have done several Google searches and not been able to find how to write a blank or null date to a datetime field in MS Sql server using ADO recordset update. Consider this example: |DATE | | null | dDATE := oRs:Fields("DATE"):Value // xHarbour sees a NULL date as NIL writing back a blank date oRs:Fields( "DATE" ):Value := IF( EMPTY( dDATE ), NIL, dDATE ) This works .. however it puts a DEFAULT date of 12/30/1899 in for the NIL parameter and writes that to the table. I need to be able to let a user blank out a date and store it as BLANK or NULL in the SQL table .. ctod("") gives an ADO run-time if you try to write that value to the MS SQL table. Any ideas ?? Rick Lipkin SC Dept of Health, USA
ADO .. how to write ctod('00/00/00') to MS Sql Server
Fernando I am writing the same program in pure ADO and in ADORDD .. I have not tested the capability of writing rdd back to the table .. and I will do that .. MS SQL seems to be different in quite a few many ways as Access or MySql .. I have put my adordd program on hold for the time being because adordd uses indexes for seeks .. and MS Sql does not support seeks on indexes .. I will test rdd on writing back ctod("00/00/00") to the table and report back here. Thanks Rick Lipkin
ADO .. how to write ctod('00/00/00') to MS Sql Server
To All .. the FIX Here is some 'snipits' of my xHarbour thread with Jose Gimenez who has fixed the problem and is available in binary from his site or on CVS. Rick Lipkin SC Dept of Health, USA //---------------------------- Rick, > This works .. however it puts a DEFAULT date of 12/30/1899 in for the NIL > parameter and writes that to the table. I need to be able to let a user > blank out a date and store it as BLANK or NULL in the SQL table .. > ctod("") gives an ADO run-time if you try to write that value to the MS > SQL table. This was fixed last Feb, 16th, but last official binaries from xHarbour are older, so you have to update from CVS. Now, writing a ctod("") value results in a real NULL date. //-------------------------------------------- The change is very simple: - search the function hb_oleItemToVariant() in \xharbour\source\rtl\win32ole.prg - search the case HB_IT_DATE: in the switch sentence - change the first line: if( bByRef ) into: if( pItem->item.asDate.value == 0 ) { pVariant->n1.n2.vt = VT_NULL; } else if( bByRef ) That's all <!-- s;-) --><img src="{SMILIES_PATH}/icon_wink.gif" alt=";-)" title="Wink" /><!-- s;-) -->
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
hi, i "read" *.XLSx using ADO to display in XBROWSE that "sems" to work ... so far but LEN of ALL FIELDs are "maximum" LEN <!-- s:shock: --><img src="{SMILIES_PATH}/icon_eek.gif" alt=":shock:" title="Shocked" /><!-- s:shock: --> --- does Function FWAdoStruct(objRS) work only on "active" Record <!-- s:?: --><img src="{SMILIES_PATH}/icon_question.gif" alt=":?:" title="Question" /><!-- s:?: --> using FWAdoStruct(objRS, .T.) i got e.g. [quote:2exrriu4]{CHINAART, C, 255, 0, 202, .T., 255, 0, 255, 255}[/quote:2exrriu4] 8th Element Type "C" is 0 while in DBF FIELD is EMPTY() in 1st Record --- any Idea what i can do ... <!-- s:idea: --><img src="{SMILIES_PATH}/icon_idea.gif" alt=":idea:" title="Idea" /><!-- s:idea: -->
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
That is the issue with ADO with Excel. Whatever length you specify while creating the table, that is ignored. ADO RecordSet field object always shows oField:DefinedSize as 255.
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
[quote:3rit79qs]does Function FWAdoStruct(objRS) work only on "active" Record <!-- s:?: --><img src="{SMILIES_PATH}/icon_question.gif" alt=":?:" title="Question" /><!-- s:?: --> [/quote:3rit79qs] It should work on both existing and blank records, but let me check again. Please post a DBF Structure here so that we both work on the same structure
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
hi, [quote="nageswaragunupudi":34lzt3bv]That is the issue with ADO with Excel.[/quote:34lzt3bv] ok, understand
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
[quote="nageswaragunupudi":1vdqkomm][quote:1vdqkomm]does Function FWAdoStruct(objRS) work only on "active" Record <!-- s:?: --><img src="{SMILIES_PATH}/icon_question.gif" alt=":?:" title="Question" /><!-- s:?: --> [/quote:1vdqkomm]Please post a DBF Structure here so that we both work on the same structure[/quote:1vdqkomm] [code=fw:1vdqkomm]<div class="fw" id="{CB}" style="font-family: monospace;"><span style="color: #00C800;">Local</span> aStruct := <span style="color: #000000;">&#123;</span>                        ;<br />   <span style="color: #000000;">&#123;</span> <span style="color: #ff0000;">"TEST_C"</span>      ,<span style="color: #ff0000;">"C"</span> ,        <span style="color: #000000;">10</span>,         <span style="color: #000000;">0</span> <span style="color: #000000;">&#125;</span> ,;<br />   <span style="color: #000000;">&#123;</span> <span style="color: #ff0000;">"TEST_N"</span>      ,<span style="color: #ff0000;">"N"</span> ,        <span style="color: #000000;">10</span>,         <span style="color: #000000;">2</span> <span style="color: #000000;">&#125;</span> ,;<br />   <span style="color: #000000;">&#123;</span> <span style="color: #ff0000;">"TEST_D"</span>      ,<span style="color: #ff0000;">"D"</span> ,         <span style="color: #000000;">8</span>,         <span style="color: #000000;">0</span> <span style="color: #000000;">&#125;</span> ,; <br />   <span style="color: #000000;">&#123;</span> <span style="color: #ff0000;">"TEST_L"</span>      ,<span style="color: #ff0000;">"L"</span> ,         <span style="color: #000000;">1</span>,         <span style="color: #000000;">0</span> <span style="color: #000000;">&#125;</span>   <span style="color: #000000;">&#125;</span> <br /> <br />DbCreate<span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"TESTTYPE.DBF"</span>, aStruct, <span style="color: #ff0000;">"FOXCDX"</span> <span style="color: #000000;">&#41;</span></div>[/code:1vdqkomm] --- [code=fw:1vdqkomm]<div class="fw" id="{CB}" style="font-family: monospace;">cQuery = <span style="color: #ff0000;">"CREATE TABLE testtype ( TEST_C TEXT ( 10) , TEST_N DOUBLE , TEST_D DATE , TEST_L BIT  )"</span>  <br /> </div>[/code:1vdqkomm] [quote:1vdqkomm]var2char( aStruct ) = "{{TEST_C, C, 255, 0, 202, .T., 255, 12, 255, 255}, {TEST_N, N, 17, 2, 5, .T., 8, 8, 15, 255}, {TEST_D, D, 8, 0, 7, .T., 8, 8, 255, 255}, {TEST_L, L, 1, 0, 11, .T., 2, 2, 255, 255}}"[/quote:1vdqkomm] [code=fw:1vdqkomm]<div class="fw" id="{CB}" style="font-family: monospace;">cQuery = <span style="color: #ff0000;">"CREATE TABLE testtype ( TEST_C TEXT ( 10) , TEST_N NUMBER , TEST_D DATE , TEST_L LOGICAL  )"</span>  <br /> </div>[/code:1vdqkomm] [quote:1vdqkomm]var2char( aStruct ) = "{{TEST_C, C, 255, 0, 202, .T., 255, 12, 255, 255}, {TEST_N, N, 17, 2, 5, .T., 8, 8, 15, 255}, {TEST_D, D, 8, 0, 7, .T., 8, 8, 255, 255}, {TEST_L, L, 1, 0, 11, .T., 2, 2, 255, 255}}" [/quote:1vdqkomm]
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
FWAdoStruct() gets the information from each field object of the RecordSet. The issue with ADO for Excel is, whatever length of char we specify it always returns 255. oField:DefinedSize. Please try this: [code=fw:r5paqw7q]<div class="fw" id="{CB}" style="font-family: monospace;"> &nbsp; n := <span style="color: #000000;">0</span><br />&nbsp; &nbsp;aFields := <span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">do</span> <span style="color: #00C800;">while</span> n < oRs:<span style="color: #000000;">Fields</span>:<span style="color: #0000ff;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; WITH OBJECT oRs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span> n <span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;AAdd<span style="color: #000000;">&#40;</span> aFields, <span style="color: #000000;">&#123;</span> :<span style="color: #0000ff;">Name</span>, :<span style="color: #000000;">Value</span>, :<span style="color: #000000;">Type</span>, :<span style="color: #000000;">DefinedSize</span>, :<span style="color: #000000;">ActualSize</span>, :<span style="color: #000000;">Precision</span>, :<span style="color: #000000;">NumericScale</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; END<br />&nbsp; &nbsp;<span style="color: #00C800;">enddo</span><br />&nbsp; &nbsp;XBROWSER aFields<br />&nbsp;</div>[/code:r5paqw7q] Whatever FWAdoStruct() shows is what ADO informs us.
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
hi, i have found this [quote:15kfqx2v]You need ADOX to do it. This is how you would create the excel file [code=fw:15kfqx2v]<div class="fw" id="{CB}" style="font-family: monospace;">Dim cat As ADOX.Catalog<br />Dim tbl As ADOX.Table<br />Dim col As ADOX.Column<br /><br />Set cat = <span style="color: #00C800;">New</span> ADOX.Catalog<br /><br />cat.ActiveConnection = <span style="color: #ff0000;">"Provider=Microsoft.Jet.OLEDB.4.0;"</span> & <span style="color: #ff0000;">"Data Source="</span><br />& myfile & <span style="color: #ff0000;">";Extended Properties=Excel 8.0"</span><br />Set tbl = <span style="color: #00C800;">New</span> ADOX.Table<br />tbl.<span style="color: #0000ff;">Name</span> = <span style="color: #ff0000;">"Sample"</span><br /><br /><span style="color: #ff0000;">'do this for each column in the table<br />Set col = New ADOX.Column<br />With col<br />.Name = "myTipe"<br />.Type = adVarWChar<br />.DefinedSize = 80<br />End With<br />tbl.Columns.Append col</span></div>[/code:15kfqx2v] .... You can then open the file with ADO to write your info [/quote:15kfqx2v] other Sample [quote:15kfqx2v][code=fw:15kfqx2v]<div class="fw" id="{CB}" style="font-family: monospace;">Sub Main<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br /><span style="color: #0000ff;">On</span> Error GoTo CreateAutoIncrColumnError<br /><br />Dim cnn As <span style="color: #00C800;">New</span> ADODB.Connection<br />Dim cat As <span style="color: #00C800;">New</span> ADOX.Catalog<br />Dim tbl As <span style="color: #00C800;">New</span> ADOX.Table<br /><br />cnn.Open <span style="color: #ff0000;">"Provider=Microsoft.Jet.OLEDB.4.0;"</span> & <span style="color: #ff0000;">"Data Source="</span> & <span style="color: #ff0000;">"C:<span style="color: #000000;">\T</span>est.XLS"</span> & <span style="color: #ff0000;">";Extended Properties=Excel 8.0"</span> Set cat.ActiveConnection = cnn<br /><br />With tbl<br />.<span style="color: #0000ff;">Name</span> = <span style="color: #ff0000;">"MyContacts"</span><br />Set .ParentCatalog = cat<br /><span style="color: #ff0000;">' Create fields and append them to the new Table object.<br />.Columns.Append "ContactId", adInteger<br />'</span> Make the ContactId column and auto incrementing column<br />.Columns<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ContactId"</span><span style="color: #000000;">&#41;</span>.Properties<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"AutoIncrement"</span><span style="color: #000000;">&#41;</span> = <span style="color: #00C800;">True</span><br />.Columns.Append <span style="color: #ff0000;">"CustomerID"</span>, adVarWChar<br />.Columns.Append <span style="color: #ff0000;">"FirstName"</span>, adVarWChar<br />.Columns.Append <span style="color: #ff0000;">"LastName"</span>, adVarWChar<br />.Columns.Append <span style="color: #ff0000;">"Phone"</span>, adVarWChar, <span style="color: #000000;">20</span><br />.Columns.Append <span style="color: #ff0000;">"Notes"</span>, adLongVarWChar<br />End With<br /><br />cat.Tables.Append tbl<br /><br /><br />cnn.Close<br />Set cat = Nothing<br />Set tbl = Nothing<br />Set cnn = Nothing<br />Exit Sub<br /><br />CreateAutoIncrColumnError:<br /><br /><span style="color: #000000;">Set</span> cat = Nothing<br />Set tbl = Nothing<br /><br /><span style="color: #00C800;">If</span> Not cnn Is Nothing Then<br /><span style="color: #00C800;">If</span> cnn.State = adStateOpen Then cnn.Close<br />End <span style="color: #00C800;">If</span><br />Set cnn = Nothing<br /><br /><span style="color: #00C800;">If</span> Err <span style="color: #000000;">0</span> Then<br />MsgBox Err.Source & <span style="color: #ff0000;">"-->"</span> & Err.Description, , <span style="color: #ff0000;">"Error"</span><br />End <span style="color: #00C800;">If</span><br /><br />End Sub</div>[/code:15kfqx2v] 100% working. (just need a correct file/path.) + Add Ref : (Menu Tools - Réf) Microsoft ADO + Microsoft ADO Ext [/quote:15kfqx2v] it is for Excel 8 so i need to change "Provider" String which is no Problem but how to handle "Set cat = New ..." <!-- s:?: --><img src="{SMILIES_PATH}/icon_question.gif" alt=":?:" title="Question" /><!-- s:?: -->
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
hi, i have ask ChatGPT and got this [code=fw:2cn8sr60]<div class="fw" id="{CB}" style="font-family: monospace;"><span style="color: #00C800;">FUNCTION</span> Main<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    <span style="color: #00C800;">LOCAL</span> cat, tbl, col<br />    cat := AdoxCreateObject<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ADOX.Catalog"</span><span style="color: #000000;">&#41;</span><br />    tbl := AdoxCreateObject<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ADOX.Table"</span><span style="color: #000000;">&#41;</span><br />    col := AdoxCreateObject<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ADOX.Column"</span><span style="color: #000000;">&#41;</span><br />    <br />    cat:<span style="color: #000000;">ActiveConnection</span> := <span style="color: #ff0000;">"Provider=Microsoft.ACE.OLEDB.12.0;"</span> + <span style="color: #ff0000;">"Data Source="</span> + myfile + <span style="color: #ff0000;">";Extended Properties='Excel 12.0 Xml;HDR=YES;'"</span><br />    <br />    tbl:<span style="color: #0000ff;">Name</span> := <span style="color: #ff0000;">"Sample"</span><br />    <br />    col:<span style="color: #0000ff;">Name</span> := <span style="color: #ff0000;">"Header1"</span><br />    col:<span style="color: #000000;">Type</span> := adVarWChar<br />    col:<span style="color: #000000;">DefinedSize</span> := <span style="color: #000000;">255</span><br />    tbl:<span style="color: #000000;">Columns</span>:<span style="color: #000000;">Append</span><span style="color: #000000;">&#40;</span>col<span style="color: #000000;">&#41;</span><br />    <br />    col:<span style="color: #0000ff;">Name</span> := <span style="color: #ff0000;">"Header2"</span><br />    col:<span style="color: #000000;">Type</span> := adDouble<br />    tbl:<span style="color: #000000;">Columns</span>:<span style="color: #000000;">Append</span><span style="color: #000000;">&#40;</span>col<span style="color: #000000;">&#41;</span><br />    <br />    col:<span style="color: #0000ff;">Name</span> := <span style="color: #ff0000;">"Header3"</span><br />    col:<span style="color: #000000;">Type</span> := adDate<br />    tbl:<span style="color: #000000;">Columns</span>:<span style="color: #000000;">Append</span><span style="color: #000000;">&#40;</span>col<span style="color: #000000;">&#41;</span><br />    <br />    col:<span style="color: #0000ff;">Name</span> := <span style="color: #ff0000;">"Header4"</span><br />    col:<span style="color: #000000;">Type</span> := adBoolean<br />    tbl:<span style="color: #000000;">Columns</span>:<span style="color: #000000;">Append</span><span style="color: #000000;">&#40;</span>col<span style="color: #000000;">&#41;</span><br />    <br />    cat:<span style="color: #000000;">Tables</span>:<span style="color: #000000;">Append</span><span style="color: #000000;">&#40;</span>tbl<span style="color: #000000;">&#41;</span><br />    <br />    <span style="color: #00C800;">LOCAL</span> conn, rs<br />    conn := HbCreateObject<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ADODB.Connection"</span><span style="color: #000000;">&#41;</span><br />    rs := HbCreateObject<span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ADODB.Recordset"</span><span style="color: #000000;">&#41;</span><br />    <br />    conn:<span style="color: #000000;">Open</span><span style="color: #000000;">&#40;</span>cat:<span style="color: #000000;">ActiveConnection</span><span style="color: #000000;">&#41;</span><br />    rs:<span style="color: #000000;">Open</span><span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"SELECT * FROM [Sample]"</span>, conn, <span style="color: #000000;">1</span>, <span style="color: #000000;">3</span><span style="color: #000000;">&#41;</span><br />    <br />    rs:<span style="color: #000000;">AddNew</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    rs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">1</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span> := <span style="color: #ff0000;">"Text Data"</span><br />    rs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">2</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span> := <span style="color: #000000;">123.45</span><br />    rs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">3</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span> := DATE<span style="color: #000000;">&#40;</span><span style="color: #000000;">2023</span>, <span style="color: #000000;">8</span>, <span style="color: #000000;">14</span><span style="color: #000000;">&#41;</span><br />    rs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">4</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span> := .T.<br />    rs:<span style="color: #0000ff;">Update</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    <br />    rs:<span style="color: #000000;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    conn:<span style="color: #000000;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    <br />    cat:<span style="color: #000000;">Tables</span>:<span style="color: #0000ff;">Refresh</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    cat:<span style="color: #000000;">Tables</span><span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"Sample"</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Columns</span>.<span style="color: #0000ff;">Refresh</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />    <br />    cat:<span style="color: #000000;">Save</span><span style="color: #000000;">&#40;</span>cat:<span style="color: #000000;">ActiveConnection</span><span style="color: #000000;">&#41;</span><br />    <br /><span style="color: #00C800;">RETURN</span> <span style="color: #00C800;">NIL</span><br /><br />PROCEDURE AdoxCreateObject<span style="color: #000000;">&#40;</span>cObjectName<span style="color: #000000;">&#41;</span><br />    <span style="color: #00C800;">LOCAL</span> oADOX<br />    oADOX := HbCreateObject<span style="color: #000000;">&#40;</span>cObjectName<span style="color: #000000;">&#41;</span><br /><span style="color: #00C800;">RETURN</span> oADOX</div>[/code:2cn8sr60] this CODE is not "perfect" but give me a Idea what to do <!-- s:idea: --><img src="{SMILIES_PATH}/icon_idea.gif" alt=":idea:" title="Idea" /><!-- s:idea: --> --- Question : if i use adVar[size=150:2cn8sr60]W[/size:2cn8sr60]Char instead of adVarChar is the same FIELD LEN <!-- s:?: --><img src="{SMILIES_PATH}/icon_question.gif" alt=":?:" title="Question" /><!-- s:?: -->
ADO / Excel / XBROWSE / FWAdoStruct() / Edit()
Yes, we can use ADOX also.
ADO /MYSQL con WBROWSE
Como se puede trabajar ADO con MYSQL con wbrowse con tablas vaciasSAludos
ADO /MYSQL con WBROWSE
Pues consistemciandolo ::oDatos:=CreateObject("adodb.Recordset") ::oDatos:CursorLocation := 2 //3 //adUseServer //adUseClient ::oDatos:LockType := 3 // adLockOptimistic ::oDatos:CursorType := 1 // adOpenKeyset ::oDatos:Source:=cStatement ::oDatos:ActiveConnection:=::oConnect ::oDatos:Open() ::cSelect := cStatementEste dato ponlo como if dentro del bline ::oDatos:Fields:Count()
ADO /MYSQL con WBROWSE
perdon es este metodoolbx:bLine:={ || if(::oDatos:RecordCount()=0,array( elem),
ADO : Building columns NULL ... DEFAULT
Hello , Working with ADO i am trying to understand field definitions as : CREATE TABLE TestTable ( ID COUNTER PRIMARY KEY , [FIELD2] CHAR(20) NOT NULL DEFAULT 'Fivewin power' , [FIELD3] NUMERIC(10,0) DEFAULT 0 ) [code=fw:2mzi6sp8]<div class="fw" id="{CB}" style="font-family: monospace;"><br />&nbsp; &nbsp;oRS:<span style="color: #000000;">AddNew</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;a := <span style="color: #000000;">&#123;</span><span style="color: #000000;">1</span>,<span style="color: #00C800;">nil</span>,<span style="color: #000000;">0</span><span style="color: #000000;">&#125;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">FOR</span> i := <span style="color: #000000;">1</span> <span style="color: #0000ff;">TO</span> oRs:<span style="color: #000000;">Fields</span>:<span style="color: #0000ff;">count</span><br />&nbsp; &nbsp; &nbsp; &nbsp;WITH OBJECT oRs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span>i<span style="color: #000000;">-1</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? :<span style="color: #000000;">Value</span> == <span style="color: #00C800;">nil</span> &nbsp; <span style="color: #B900B9;">// Give 3 times .T. , value from each field seems to be nil</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00C800;">try</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; :<span style="color: #000000;">Value</span> = a<span style="color: #000000;">&#91;</span> i <span style="color: #000000;">&#93;</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; catch <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? <span style="color: #ff0000;">" Error on field "</span> + :<span style="color: #0000ff;">Name</span> , a<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end &nbsp; <br />&nbsp; &nbsp; &nbsp; &nbsp;END<br />&nbsp; &nbsp;<span style="color: #00C800;">NEXT</span><br />&nbsp; &nbsp;oRs:<span style="color: #0000ff;">Update</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp;<span style="color: #00C800;">FOR</span> i := <span style="color: #000000;">1</span> <span style="color: #0000ff;">TO</span> oRs:<span style="color: #000000;">Fields</span>:<span style="color: #0000ff;">count</span><br />&nbsp; &nbsp; &nbsp; &nbsp;WITH OBJECT oRs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span>i<span style="color: #000000;">-1</span><span style="color: #000000;">&#41;</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? :<span style="color: #000000;">Value</span> , :<span style="color: #000000;">Value</span> == <span style="color: #00C800;">nil</span> , VALTYPE<span style="color: #000000;">&#40;</span>:<span style="color: #000000;">Value</span><span style="color: #000000;">&#41;</span> <br />&nbsp; &nbsp; &nbsp; &nbsp;END<br />&nbsp; &nbsp;<span style="color: #00C800;">NEXT</span><br /><br />&nbsp;</div>[/code:2mzi6sp8] 1) Default value has no effect. I expected the value from the second field to be 'fivewin power' 2) Second field has clause NOT NULL , but value nil is accepted. The field has now a value SPACE(20) , same result with Clause NULL 3) Third field ? :Value --> 0.00 , expected 0 , maybe configuration from the aplication (SET DECIMALS) Exact value can be retrieved using oField:Precision It seems that on this way the clauses (NOT) NULL and DEFAULT have no effect. Can this clauses be retrieved from ADO ? If not they are useless in the fivewin aplication. Frank
ADO : Building columns NULL ... DEFAULT
Assigning nil is equivalent to assigning NULL. When we assign NULL, server does not use Default value. Server thinks that we wanted the value to be NULL overriding the default value. So it is desirable to assign DEFAULT. This can be done either by omitting the assignment in SQL statement of specifically assigining DEFAULT. Now, how do we do it in ADO. Instead of using NIL, use AdoDefault(). AdoDefault() and AdoNull() are functions provided by FWH for this purpose.
ADO : Building columns NULL ... DEFAULT
Rao , I am not sure that you answered the question . Building the table with CREATE TABLE TestTable ( ID COUNTER PRIMARY KEY , [FIELD2] CHAR(20) NOT NULL DEFAULT 'Fivewin power' , ... ) .... oRs:AddNew() FIELD2 must become the value "Fivewin power" . Will Ors:Fields("FIELD2"):Value := AdoDefault() do so ? or does it the same as AdoNull() ? This function is not present in FWH1404. ( I don't use FWH for comercial purposes , ony to make a new version from FWHDBU) I found this two functions in ADORDD.PRG from 08.12.2015 , but adonull gives a nil value , adodefault a error How can give Adodefault this Defaultvalue ? How can it read this value from the ors or connection class ? Frank
ADO : Building columns NULL ... DEFAULT
Frank I am not familiar with "Default" .. I am a bit old fashioned and like to write out my code without taking too many shortcuts .. understand Rao has created some VERY nice Ado wrappers and can simplify the code below .. however, Consider this example: [code=fw:3ekvvz93]<div class="fw" id="{CB}" style="font-family: monospace;"><br /><span style="color: #B900B9;">// Assuming you have a connection to the database oCn</span><br /><br /><span style="color: #B900B9;">// easier to read if you code the Create Table this way</span><br /><br />cSql :=  <span style="color: #ff0000;">"CREATE TABLE [TestTable] "</span><br />cSql +=  <span style="color: #ff0000;">"( "</span><br />cSql += <span style="color: #ff0000;">"[Id]  COUNTER NOT NULL, "</span><br />cSql += <span style="color: #ff0000;">"[Field2]        char(20) NULL, "</span><br />cSql += <span style="color: #ff0000;">"CONSTRAINT PK_TESTTABLE PRIMARY KEY ( ID )"</span><br />cSql += <span style="color: #ff0000;">" )"</span><br /><br /><span style="color: #00C800;">Try</span><br />   oCn:<span style="color: #000000;">Execute</span><span style="color: #000000;">&#40;</span> cSQL <span style="color: #000000;">&#41;</span><br />Catch<br />   <span style="color: #0000ff;">MsgInfo</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"Create Table TESTTABLE Failed"</span> <span style="color: #000000;">&#41;</span><br />   oCn:<span style="color: #000000;">CLose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />   <span style="color: #00C800;">Return</span><span style="color: #000000;">&#40;</span>.f.<span style="color: #000000;">&#41;</span><br />End <span style="color: #00C800;">try</span><br /><br />oRs := TOleAuto<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>:<span style="color: #00C800;">New</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"ADODB.Recordset"</span> <span style="color: #000000;">&#41;</span><br />oRs:<span style="color: #000000;">CursorType</span>     := <span style="color: #000000;">1</span>        <span style="color: #B900B9;">// opendkeyset</span><br />oRs:<span style="color: #000000;">CursorLocation</span> := <span style="color: #000000;">3</span>        <span style="color: #B900B9;">// local cache</span><br />oRs:<span style="color: #000000;">LockType</span>       := <span style="color: #000000;">3</span>        <span style="color: #B900B9;">// lockoportunistic</span><br /><br />cSQL := <span style="color: #ff0000;">"SELECT * from [TestTable]"</span><br /><br /><span style="color: #00C800;">TRY</span><br />  oRS:<span style="color: #000000;">Open</span><span style="color: #000000;">&#40;</span>cSQL,oCn <span style="color: #000000;">&#41;</span><br />CATCH oErr<br />  <span style="color: #0000ff;">MsgInfo</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"Error in Opening TESTTABLE table"</span> <span style="color: #000000;">&#41;</span><br />  oCn:<span style="color: #000000;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />  <span style="color: #00C800;">RETURN</span><span style="color: #000000;">&#40;</span>.F.<span style="color: #000000;">&#41;</span><br />END <span style="color: #00C800;">TRY</span><br /><br />oRs:<span style="color: #000000;">AddNew</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />oRs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"Field2"</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span> := <span style="color: #ff0000;">"Fivewin power"</span><br />oRs:<span style="color: #0000ff;">Update</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br /><br />oRs:<span style="color: #000000;">CLose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />oCn:<span style="color: #000000;">CLose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br /><br /><span style="color: #00C800;">Return</span><span style="color: #000000;">&#40;</span>.t.<span style="color: #000000;">&#41;</span><br /> </div>[/code:3ekvvz93] Rick Lipkin
ADO : Building columns NULL ... DEFAULT
Rick He is writing a generic DBU. How does he know what value to be assigned? [quote:336nykb8] oRs:Fields("Field2"):Value := "Fivewin power" [/quote:336nykb8] How does he know that the default value is "Fivewin power" ? That is the question he is asking.
ADO : Building columns NULL ... DEFAULT
Rao , ADO has not the possibility to retrieve the Default value ? Wright ? It is not difficult to build DBU , writing the Default values in an ini-file when the table is created with DBU. But opening an ADO file , created outside DBU , the default value can't be retrieved (i suppose) Frank
ADO : Building columns NULL ... DEFAULT
ADO does not retrieve default values. ADO converts all Save()s into INSERT or UPDATE SQL statements and executes on the server. Assigning a NULL value also over-rides default. Through SQL, the ways to write default values are (1) do not specify a value for the field or (2) specify DEFAULT as value for the field. Eg: INSERT INTO TestTable ( [field1], [field2] ) VALUES ( somevalue, DEFAULT ) or INSERT INTO TestTable( [field1] ) VALUES ( somevalue ) // We do not list ID and field2 here Now how to do this with ADO? We have seen that assigning a value of NIL and saving is equivalent to specify NULL in the INSERT sql statement. So default value is not used. So, oRs:AddNew() Assign fields with nil or some value oRs:Save() does not work. Only way is: oRs:AddNew( aFields, aValues ) // oRs:Save() is not required for this usage without including autoinc and default value fields in the list (array) Eg: oRs:AddNew( { "field1" }, { 24 } ) // 24 is some value. We did not include ID and FIELD2 in this list. This writes correctly to the database assiging "Fivewin power" to FIELD2 and also autoincrementing ID. Still our client does not know what are the values written, We need to re-read the values written with either oRs:ReSync( 1, 2 ) or oRs:Requery() Unfortunately Resync() does not work perfectly with all databases. Works perfectly with MSSQL and Requery() is slow but works in all cases Tested just now. Adodefault() is not working. As to the code we can always share with you wherever necessary. But this is not working here. May I know are you developing in Harbour or xHarbour?
ADO : Building columns NULL ... DEFAULT
[quote:2npqwgm0]It is not difficult to build DBU , writing the Default values in an ini-file when the table is created with DBU. [/quote:2npqwgm0] Assigning default values explicitly is not proper. This is the job of the server and we should let the server do it. The way is to use AdoNew( <fields>, <values> )
ADO : Entorno Multiusuario Ayuda (Solucionado)
Un saludo a todos los colegas del Foro Estoy largo rato intentando encontrar la solución a este problema y me doy por vencido. He implementado un BROWSE en el cual se dan las típicas opciones de Modificar, Adicionar y Eliminar Registros, usando los métodos del objeto Recordset de ADO. Funciona Muy bien cuando se trabaja con una sola estación (estacion1); pero cuando desde estacion2 se realiza algún cambio, adición o eliminación, estos no se reflejan en el Browse de estacion1. Entonces si por ejemploi el usuario de estacion1 trata de eliminar lo que estacion2 ya eliminó se produce el consiguiente error devuelto por el proveedor OLEDB. La localización del Cursor está definido del lado del cliente oRs:CursorLocation = adUseClient El Objeto se abre usando estos parámetros oRs:Open( cQuery , cConnection, adOpenKeyset, adLockOptimistic ) incluso he probado usando adOpenDynamic, que según los manuales permiten ver todo tipo de cambios de otros usuarios, pero nada. He tratado de probar usando las propiedades OriginalValue y UnderlyingValue (valor que tiene en la base de datos) pero los valores que se obtiene son los mismos que tiene el recordset en ese momento, no permitiéndome controlar el valor actual en la base de datos y el valor actual en el recordset local. Cómo podría refrescar el BROWSE de estacion1 con los nuevos cambios ocurridos en El Servidor de Base de Datos y que lo realizó estacion2? Pienso que si uso Requery() cada momento que me muevo por cada elemento del Browse, en una tabla grande y en internet se volvería muy lenta y el moverme sería un caos, porque en el requery se recargan los datos y el cursor siempre va a la ultima fila. Una opción que se me ocurre es capturar los mensajes de error del proveedor OLEDB y en base a estos actuar recargando los nuevos datos. Pero esta parte es la que no se como hacerlo aún. Cómo hago con Harbour para capturar los errores de ADO? Espero que alguien pueda darme alguna pista o si ya lo tiene resuelto me indique cómo controlar esos cambios. Desde ya muy agradecido Marcelo Jingo
ADO : Entorno Multiusuario Ayuda (Solucionado)
Marcelo, Para conseguir un 'browse' a lo xBase debes tener en cuenta: a. Que el proveedor que utilizas sea capaz de manejar cursores dinámicos. b. Que abras un recordset cliente y dinámico. No obstante lo anterior, abrir un recordset de esas características, cuando hay varios terminales 'atacando' al mismo 'browse' puede que el servidor se atasque. Si necesitas más información puedes mirar la ayuda de ADO y tambien puedes echar un vistazo a este artículo [url:3o7znfs4]http&#58;//www&#46;capelblog&#46;com/?p=58[/url:3o7znfs4]
ADO : Entorno Multiusuario Ayuda (Solucionado)
Gracias por tu interés José Luis. Seguiré buscando la forma..., creo que en este punto voy a tener que hacer consultas SQL independientes usando el objeto command para comparar entre el valor actual del field del recordset y el que me entregue la consulta.... seguiré probando Un saludo Marcelo Jingo
ADO : Entorno Multiusuario Ayuda (Solucionado)
Marcelo, [quote:darcis7y]Seguiré buscando la forma..., creo que en este punto voy a tener que hacer consultas SQL independientes usando el objeto command para comparar entre el valor actual del field del recordset y el que me entregue la consulta.... seguiré probando [/quote:darcis7y] Quizás no te he entendido bien... ¿Te refieres a tener un recordset con actualización dinámica o te refieres a la actualización de una fila?
ADO : Entorno Multiusuario Ayuda (Solucionado)
José Luis, Como dije, si un solo usuario se conecta al Servidor de Base de Datos(MySQL), no hay problema, el browse del recordset trabaja muy bien realizando actualizaciones, altas o eliminando registros, usando sus respectivos métodos, cuyas modificaciones se reflejan inmediátamente en el Servidor. Pero si 2 o más usuarios usan el mismo recordset y uno de ellos por ejemplo elimina un registro, este cambio no se refleja en el browse del otro usuario, pudiendo este último (que aún lo ve en su browse) tratar de eliminar el que ya no existe en la Base de Datos, haciendo que se genere un error. Lo más fácil sería colocar un botón que ejecute el método Requery, y que el usuario lo ejecutaría cada vez que vaya a realizar un cambio y así tenga la versión más actual de los datos. Pero esto no me parece muy práctico. Es por eso que yo me inclinaba por el lado de capturar los Errores del Proveedor de OLEDB, para que sólo cuando se genere el error mostrar el mensaje respectivo, y luego hacer un requery o regenerar todo el recordsete. Por eso va mi pedido a quienes puedan ayudarme y guiarme en este asunto. De antemano muchas gracias Saludos Marcelo Jingo
ADO : Entorno Multiusuario Ayuda (Solucionado)
Amigo y por que no simplemente colocas un timer() para que refresque el browse, creo que esto soluciona tu problema. Un Saludos LEANDRO ALFONSO
ADO : Entorno Multiusuario Ayuda (Solucionado)
Saludos Leandro Si no puedo capturar los errores desde Harbour, probaré pasándome a xHarbour que allí sí creo que se puede capturarlos usando TRY CATCH END. Si eso no funciona trataré de utilizar el TIMER que me recomiendas. Lo que se intenta es que la aplicación consuma menos recursos tanto del equipo como e la red. Seguiré con mis pruebas y ya les comentaré. Gracias Leandro Marcelo Jingo
ADO : Entorno Multiusuario Ayuda (Solucionado)
Es necesario un timer cuando se usa un browse para monitorear los datos, activate dialog oDlg centered on init ( mitimerOn() ) static function MiTimerOn() DEFINE TIMER oTimer of oDlg INTERVAL 5000 ACTION TimerAction() activate timer oTimer return
ADO : Entorno Multiusuario Ayuda (Solucionado)
César y Leandro He probado colocando el timer, en efecto funciona ..... peeero, sucede lo que ya esperaba, que apenas si estoy navegando por el browse, este se va a la primera fila, cada intervalo que se ha definido el timer. impidiendo una navegación limpia. Creo que tendré que implementar un control más riguroso en el recordest, como guardar el número de fila actual y al refrescar volver a la fila gusadada y............ más cosas. De todas formas gracias por todo y seguiré probando, es más ya me pasé a xHarbour para probar el control de errores con TRY CATCH. Un Saludo Marcelo Jingo
ADO : Entorno Multiusuario Ayuda (Solucionado)
Marcelo, ¿Puedes mostrarnos cómo creas el recordset? ¿Contra cual base de datos? ¿Cual proveedor usas?
ADO : Entorno Multiusuario Ayuda (Solucionado)
Gracias José Luis, César y Leandro. Con el apoyo de todos ya lo he solucionado y me funciona perfecto. La solución fue colocar el timer y controlando los posibles errores que podemos encontrar en la navegación. Gracias de nuevo. Marcelo Jingo
ADO : doesn't work anymore
Hello , I used to work with ADO (mdb-files) , till last month no problems. Since then i can't changed data in a mdb-file , i.e. (see also <!-- l --><a class="postlink-local" href="http://forums.fivetechsupport.com/viewtopic.php?f=3&t=33115">viewtopic.php?f=3&t=33115</a><!-- l -->) [code=fw:2xs7mikh]<div class="fw" id="{CB}" style="font-family: monospace;"><br />oRs &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; := TOleAuto<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>:<span style="color: #00C800;">New</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"ADODB.Recordset"</span> <span style="color: #000000;">&#41;</span><br />oRs:<span style="color: #000000;">CursorType</span> &nbsp; &nbsp; &nbsp;:= <span style="color: #000000;">1</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #B900B9;">// opendkeyset</span><br />oRs:<span style="color: #000000;">CursorLocation</span> &nbsp;:= <span style="color: #000000;">3</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #B900B9;">// local cache</span><br />oRs:<span style="color: #000000;">LockType</span> &nbsp; &nbsp; &nbsp; &nbsp;:= <span style="color: #000000;">3</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #B900B9;">// lockoptimistic</span><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br /><span style="color: #00C800;">try</span><br />&nbsp; &nbsp;oRs:<span style="color: #000000;">Open</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"SELECT * FROM "</span> + cTable, oCon <span style="color: #000000;">&#41;</span> <span style="color: #B900B9;">// Password="abc" )</span><br />catch oError<br />&nbsp; &nbsp;<span style="color: #0000ff;">MsgInfo</span><span style="color: #000000;">&#40;</span> oError:<span style="color: #000000;">Description</span> <span style="color: #000000;">&#41;</span><br />end<br />? &nbsp;oRs:<span style="color: #000000;">CursorType</span> , oRs:<span style="color: #000000;">CursorLocation</span> , oRs:<span style="color: #000000;">LockType</span> &nbsp;<span style="color: #B900B9;">// 3,3,3 !!!!!</span><br /><span style="color: #B900B9;">// Is it normal that cursortype is changed in 3 ? &nbsp;</span><br /><br />DBG oRs &nbsp;<span style="color: #B900B9;">// Shows correct</span><br /><br />oRs:<span style="color: #000000;">MoveFirst</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />oRs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"ROW2"</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span> := <span style="color: #ff0000;">"Test"</span><br />oRs:<span style="color: #0000ff;">Update</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> &nbsp; <= ERROR , due <span style="color: #0000ff;">to</span> previous line<br />&nbsp;</div>[/code:2xs7mikh] Error description: (DOS Error -2147352567) WINOLE/1007 Kan de bij te werken rij niet vinden. Sommige waarden zijn mogelijk veranderd sinds de rij voor het laatst is gelezen. (0x80040E38): Microsoft Cursor Engine (Can not fint row to work on. Some values can be changed after the row was read) Also when i try to use older versions from fivedbu i get this error. The most recent doesn't generate a error but doesn't changed the data I suppose something has changed in the environnement , but i have no idea to restore it. Is there a key in regedit ? Maybe a download ? Frank
ADO : doesn't work anymore
Franklin see this post : <!-- l --><a class="postlink-local" href="http://forums.fivetechsupport.com/viewtopic.php?f=3&t=26102&start=15">viewtopic.php?f=3&t=26102&start=15</a><!-- l --> Rick Lipkin
ADO : doesn't work anymore
[quote:1toj9ef4] ? oRs:CursorType , oRs:CursorLocation , oRs:LockType // 3,3,3 !!!!! // Is it normal that cursortype is changed in 3 ? [/quote:1toj9ef4] Always and at all times, a client side record-set is opened with cursor-type adOpenStatic only, whatever cursortype we specify while opening the recordset. In other words, it is just useless and meaningless for us to specify a cursor type while openining a recordset with cursorlocation adUseClient. This has been the behavior since ADO was created. There is nothing surprising or unusual about it. Again, it is not that ADO was made like that. It is because with all RDBMSs, all client side cursors are static cursors. Exceptions are (1) ADS and (2) one table at a time per one connection of MSSQL.
ADO ???
Hola a todos del foro Disculpen mi ignorancia, pero quiero saber Que es ADO, para que sirve, en que se utiliza. Es que quiero migrar mis sistemas a Cliente/Servidor. Salu2 Francis
ADO ???
<!-- m --><a class="postlink" href="http://es.wikipedia.org/wiki/ActiveX_Data_Objects">http://es.wikipedia.org/wiki/ActiveX_Data_Objects</a><!-- m -->
ADO AbsolutePosition in 64bit problem
Hi, In my 32bit version I use this code to update a query, and stay on the same record. [code=fw:gwgrw5gv]<div class="fw" id="{CB}" style="font-family: monospace;">vrec := oRs:<span style="color: #000000;">AbsolutePosition</span><br />oRs:<span style="color: #000000;">Requery</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />oRs:<span style="color: #000000;">AbsolutePosition</span><span style="color: #000000;">&#40;</span>vrec<span style="color: #000000;">&#41;</span></div>[/code:gwgrw5gv] and is working fine. In the 64bit-version I receive an error on the 3the line where I set the position again. vrec is holding the line-number, just like in the 32bit version. I debugged it, and is the value of the record, just like in the 32-bit version. [code=fw:gwgrw5gv]<div class="fw" id="{CB}" style="font-family: monospace;">Error description: <span style="color: #000000;"><span style="color: #000000;">&#40;</span>DOS</span> Error <span style="color: #000000;">-2147352562</span><span style="color: #000000;">&#41;</span> WINOLE/<span style="color: #000000;">1007</span>  Argument error: <span style="color: #000000;">ABSOLUTEPOSITION</span><br />Args:<br />   <span style="color: #000000;">&#91;</span>   <span style="color: #000000;">1</span><span style="color: #000000;">&#93;</span> = N   <span style="color: #000000;">2</span></div>[/code:gwgrw5gv] Is there another way to do this?
ADO AbsolutePosition in 64bit problem
Marc You can always do this the brute force way by saving your primary key to a variable and then requery and go back and find .. [code=fw:24e6phhp]<div class="fw" id="{CB}" style="font-family: monospace;"><br /><span style="color: #00C800;">Local</span> nPrimKey<br /><br />nPrimKey := oRs:<span style="color: #000000;">Fields</span><span style="color: #000000;">&#40;</span><span style="color: #ff0000;">"<your nPrim key>"</span><span style="color: #000000;">&#41;</span>:<span style="color: #000000;">Value</span><br />oRs:<span style="color: #000000;">ReQuery</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br /><br />oRs:<span style="color: #000000;">MoveFirst</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><br />oRs:<span style="color: #000000;">Find</span><span style="color: #000000;">&#40;</span> <span style="color: #ff0000;">"<your nPrim key> = "</span>+ltrim<span style="color: #000000;">&#40;</span>str<span style="color: #000000;">&#40;</span>nPrimKey<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><br /> </div>[/code:24e6phhp] May not be pretty, but it should work.. Rick Lipkin
ADO AbsolutePosition in 64bit problem
Hi, I found the solution. <!-- s:D --><img src="{SMILIES_PATH}/icon_biggrin.gif" alt=":D" title="Very Happy" /><!-- s:D --> [code=fw:1fwbxd9x]<div class="fw" id="{CB}" style="font-family: monospace;">oRs:<span style="color: #000000;">AbsolutePosition</span> := vrec</div>[/code:1fwbxd9x] is working Strange that in the other release [code=fw:1fwbxd9x]<div class="fw" id="{CB}" style="font-family: monospace;">oRs:<span style="color: #000000;">AbsolutePosition</span><span style="color: #000000;">&#40;</span>vrec<span style="color: #000000;">&#41;</span></div>[/code:1fwbxd9x] also works <!-- s:shock: --><img src="{SMILIES_PATH}/icon_eek.gif" alt=":shock:" title="Shocked" /><!-- s:shock: -->
ADO AbsolutePosition in 64bit problem
Marc I like your solution much better and more elegant. Thanks for the feedback! Rick Lipkin
ADO AbsolutePosition in 64bit problem
[quote="Marc Vanzegbroeck":229g19la]Hi, I found the solution. <!-- s:D --><img src="{SMILIES_PATH}/icon_biggrin.gif" alt=":D" title="Very Happy" /><!-- s:D --> [code=fw:229g19la]<div class="fw" id="{CB}" style="font-family: monospace;">oRs:<span style="color: #000000;">AbsolutePosition</span> := vrec</div>[/code:229g19la] is working Strange that in the other release [code=fw:229g19la]<div class="fw" id="{CB}" style="font-family: monospace;">oRs:<span style="color: #000000;">AbsolutePosition</span><span style="color: #000000;">&#40;</span>vrec<span style="color: #000000;">&#41;</span></div>[/code:229g19la] also works <!-- s:shock: --><img src="{SMILIES_PATH}/icon_eek.gif" alt=":shock:" title="Shocked" /><!-- s:shock: -->[/quote:229g19la] AbsolutePosition isn't a method so the assignment is the correct way. EMG
ADO AbsolutePosition in 64bit problem
I'm not certain which class is in use in this case, but looking at the source to TArrData and TRecSet I see that AbsolutePosition is an access value, and AbsolutePosition() is an assignment method. Give this I would expect oRS:AbsolutePosition := N to fail. ---------- TARRDATA.PRG ACCESS AbsolutePosition INLINE ::nAt ASSIGN AbsolutePosition( x ) INLINE ::nAt := x ---------- TRECSET.PRG ACCESS AbsolutePosition INLINE If( ::Empty, 0, ::oRs:AbsolutePosition ) ASSIGN AbsolutePosition( n ) ; INLINE If( ::Empty, nil, ::oRs:AbsolutePosition := ::rs_FitRange( n ) )
ADO AbsolutePosition in 64bit problem
AbsolutePosition is a property not a method. Please look at the MS docs: [url:9zcaq4ao]https&#58;//msdn&#46;microsoft&#46;com/en-us/library/ms676594(v=vs&#46;85)&#46;aspx[/url:9zcaq4ao] EMG
ADO Absoluteposition
To All I am running a roadblock and need to be able to store a recno to an array of 10 records. The only way I know how to update a record was to store the record number of the table in an element. WHen I go update the rows .. I just goto nRecno and Update my variables. I do not have a problem getting a "suedo" record number with : nRec := oRs:AbsolutePosition // -- get recno() oRs:AbsolutePosition := nRec // -- goto nRecno However since a recordset is not exactically a static commodity .. what are the pros and cons of using the above logic in moving between ( suedo ) records ?? Unforunitly .. creating a unique sequence id per record is not an option. Thanks Rick Lipkin SC Dept of Health, USA