Page 1 of 1

Funcion de MySQL nativa en codigo

PostPosted: Sat Oct 01, 2022 1:59 pm
by nlerdafehn
Hola Foro!

Estuve buscando ya hace un tiempo y no logro encontrar como hacerlo. Estoy usando dolphin para comunicarme con MySQL, y estoy usando esto de fivewin pero no logro ver como hacer para utilizar una funcion de MySQL en el insert. Siempre tengo que recaer en escribir el insert a mano si quiero utilizar alguna función de MySQL.

Les doy un ejemplo: Si yo tengo una columna de control de cuando se realizo el momento, en el insert de MySQL en ese campo, le ejecuto la funcion now(), que es un timestamp de fecha, hora y segundos. En cuanto a la manera que lo utilizo, no se como hacer para que tome una función de SQL, ya que no quiero que tome time() de harbour, porque va a tomar la hora local de la PC que es alterable, ni tampoco quiero hacer una query preguntando el now y despues insertarlo. Hay alternativas, lo se. Pero quisiera que fluya mejor y si hay alguna manera de hacer que la función de MYSQL se pueda poner.

Ejemplo de codigo

Code: Select all  Expand view
ntab:=oodbc:query('select * from ventas limit 0')
  ntab:getblankrow(.f.)
  ntab:caja  := hvnum["caja"]
  ntab:fecha   := date() // aca toma la fecha de la PC, pero quisiera hacer la funcion current_date() de mysql
  ntab:momento := date() +" " +time() // aca me gustaria poner now()
  ntab:cliente   := "A Consumidor Final"
  ntab:save()
  ntab:end()


Espero sus comentarios,
Buen finde!

Re: Funcion de MySQL nativa en codigo

PostPosted: Sat Oct 01, 2022 3:07 pm
by cmsoft
Creo que con Save() no se puede porner el valor de una funcion MySql sobre el Objeto Query
Podrias hacerlo asi:
Code: Select all  Expand view

ntab:=oodbc:query('select * from ventas limit 0')
  oRow := ntab:getblankrow(.f.)
  oRow:caja  := hvnum["caja"]
  oRow:fecha   := oodbc:query("select curdate() as fecha from dual"):fecha
  oRow:momento := oodbc:query("select now() as hora from dual"):hora
  oRow:cliente   := "A Consumidor Final"
  ntab:oRow := oRow
  ntab:save()
  ntab:end()

 

Sino, tambien puedes dejarle el trabajo a la base de datos, definiendo la tabla para que el campo lo llene solo
Code: Select all  Expand view

CREATE TABLE mitabla (
   momento DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
 

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 11:21 am
by nageswaragunupudi
cmsoft wrote:Sino, tambien puedes dejarle el trabajo a la base de datos, definiendo la tabla para que el campo lo llene solo
Code: Select all  Expand view

CREATE TABLE mitabla (
   momento DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
 


The above is recommended.

In the above case, MySql server fills the field `momento` with correct DateTime value at the time of insertion of the row. This value will not change when any fields of the record are modified.
See another variant:
Code: Select all  Expand view
CREATE TABLE mitabla (
   momento DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `modify_dt`  TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
 

MySql server updates the value of `modify_dt` everytime any field in the record is updated.

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 12:07 pm
by cmsoft
Muchas gracias Mr. Rao por la explicación.
En el caso de lo que solicita Nicolás, que es también un campo DATE (no DATETIME) que se llene con la fecha de creación, el único camino es crear una trigger que lo haga?

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 2:30 pm
by carlos vargas
Tener cuidado con la fecha y hora del sever, por si esta en un hosting.

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 3:48 pm
by nageswaragunupudi
carlos vargas wrote:Tener cuidado con la fecha y hora del sever, por si esta en un hosting.

i do not have any problem with TIMESTAMP even on cloud hosted servers.
Can you please explain the problems you face.

Better we discuss.

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 4:20 pm
by nageswaragunupudi
cmsoft wrote:Muchas gracias Mr. Rao por la explicación.
En el caso de lo que solicita Nicolás, que es también un campo DATE (no DATETIME) que se llene con la fecha de creación, el único camino es crear una trigger que lo haga?


You are right in case of all MySQL versions prior to 8.0.13.
In later versions, this works:
Code: Select all  Expand view
`createdate` DATE NOT NULL DEFAULT (CURRENT_DATE)

I just tested.

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 4:41 pm
by cmsoft
Excelente Mr. Rao, lo había leído pero intenté en algunas bases con versiones anteriores y no funcionaba.
Es cuestión de actualizar la versión de MySql

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 5:18 pm
by nageswaragunupudi
You can test on our cloud server version 8.0.29
"209.250.245.152",
database: "fwh",
user: "fwhuser",
pwd : "FiveTech@2022"

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 6:26 pm
by nageswaragunupudi
We need to explore more with MariaDB.
I read that DEFAULT (expression) works from version 10.2.1

Re: Funcion de MySQL nativa en codigo

PostPosted: Mon Oct 03, 2022 7:33 pm
by cmsoft
Probé en mi base de datos local
Code: Select all  Expand view

ALTER TABLE `test`.`art524`  
  ADD COLUMN `fecha_alta` DATE  DEFAULT (CURRENT_DATE)  ;
Resultado
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(CURRENT_DATE)' at line 2
 

Version 10.0.24-MariaDB
Voy a tratar de actualizar la versión y hacer las pruebas

En mi base remota:
8.0.30-0ubuntu0.20.04.2
El resultado correcto

Re: Funcion de MySQL nativa en codigo

PostPosted: Tue Oct 04, 2022 12:46 am
by nageswaragunupudi
With MariaDB, use (CURRENT_DATE()) not (CURRENT_DATE).

With MySQL 8.0.28. both (CURRENT_DATE) and (CURRENT_DATE()) are working.

Re: Funcion de MySQL nativa en codigo

PostPosted: Tue Oct 04, 2022 2:19 am
by nageswaragunupudi
Small Test:
Code: Select all  Expand view
#include "fivewin.ch"

function Main()

   local oCn, oRs

   SET DATE ITALIAN
   SET CENTURY ON

   oCn   := maria_Connect( "209.250.245.152","fwh","fwhuser","FiveTech@2022" )
   oCn:lShowErrors   := .t.
   ? oCn:cServerInfo
   xbrowser ocn:ListTables()

   oCn:DropTable( "dt" )

   ? oCn:CreateTable( "dt", { ;
      { "NAME", "C", 10, 0 }, ;
      { "NUMB", "N", 10, 0 }, ;
      { "CRDT1", "DATE NOT NULL DEFAULT (CURRENT_DATE)", 8, 0 }, ;
      { "CRDT2", "DATE NOT NULL DEFAULT (CURRENT_DATE())", 8, 0 }, ;
      { "CRDTT", "@", 8, 0 }, ;
      { "UPDTT", "=", 8, 0 } } )
     
   FW_MemoEdit( oCn:CreateTableSQL( "dt" ) )

   oRs := oCn:dt
   oRs:Edit()
   xbrowser oRs FASTEDIT

   oCn:Close()

return nil
 


Result of oCn:CreateTableSQL( "dt" ):
Code: Select all  Expand view
CREATE TABLE `dt` (
  `id` int NOT NULL AUTO_INCREMENT,
  `NAME` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8_unicode_ci DEFAULT NULL,
  `NUMB` bigint DEFAULT NULL,
  `CRDT1` date NOT NULL DEFAULT (curdate()),
  `CRDT2` date NOT NULL DEFAULT (curdate()),
  `CRDTT` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `UPDTT` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8_unicode_ci



Image

Re: Funcion de MySQL nativa en codigo

PostPosted: Tue Oct 04, 2022 3:02 am
by cmsoft
Muy buen ejemplo.
Aprovecho para consulta: como actualizo mi versión de MariaDB para Windows? Se ejecuta un nuevo instalador con la versión elegida o hay otra manera?

Re: Funcion de MySQL nativa en codigo

PostPosted: Tue Oct 04, 2022 6:26 am
by xmanuel
Creo que lo que quiere hacer Nicolás es usar funciones nativas de MySQL...
Por lo tanto lo mejor es que construya la sentencia INSERT manualmente.