Dúvida inserir data no MySql
Moderador: Moderadores
Dúvida inserir data no MySql
olá pessoal,
Estou tentando inserir dados na tabela CLIENTES, mas se o usuário não informar a data de nascimento, quero gravar o campo
com uma variável vazia mas ocorre um erro e o MySql não está aceitando, como ficaria o comando abaixo, pois no insert não
tenho como verificar se a variavel esta vazia ou não.
dtnascimento = ""
string sql = "INSERT INTO CLIENTES (CLI_NASCEU) VALUES (dtnascimento);
Obrigado.
Estou tentando inserir dados na tabela CLIENTES, mas se o usuário não informar a data de nascimento, quero gravar o campo
com uma variável vazia mas ocorre um erro e o MySql não está aceitando, como ficaria o comando abaixo, pois no insert não
tenho como verificar se a variavel esta vazia ou não.
dtnascimento = ""
string sql = "INSERT INTO CLIENTES (CLI_NASCEU) VALUES (dtnascimento);
Obrigado.
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Código: Selecionar todos
FUNCTION DateSql( dDate )
LOCAL cString
cString := StrZero( Year( dDate ), 4 ) + "-" + StrZero( Month( dDate ), 2 ) + "-" + StrZero( Day( dDate ), 2 )
IF cString == "0000-00-00"
cString := "NULL"
ELSE
cString := StringSql( cString )
ENDIF
RETURN cString
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Dúvida inserir data no MySql
Sem precisar mexer no fonte, ajuste o campo na sua tabela para ter o valor padrão caso não venha no INSERT, tipo 0000:00:00 (se for DATE) ou 0000:00:00 00:00:00 (se for DATETIME).
Exemplo:
Exemplo:
Até+ALTER TABLE `city` CHANGE `DatadoDia` `CountryCode` DATETIME CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '0000:00:00 00:00:00';
Clipper 5.2e / Blinker 5.1 / Harbour 3.2 / GTwvg
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Lembrando que data zerada não é padrão em SQL.
Se o MySQL estiver com STRICT MODE ativado também não aceita data zerada.
O padrão pra qualquer campo sem nada é NULL, que equivaleria ao NIL do Clipper/Harbour.
Se o MySQL estiver com STRICT MODE ativado também não aceita data zerada.
O padrão pra qualquer campo sem nada é NULL, que equivaleria ao NIL do Clipper/Harbour.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Dúvida inserir data no MySql
Sem precisar mexer no fonte, ajuste o campo na sua tabela para ter o valor padrão caso não venha no INSERT, tipo 0000:00:00 (se for DATE) ou 0000:00:00 00:00:00 (se for DATETIME).
Exemplo:
ALTER TABLE `city` CHANGE `DatadoDia` `CountryCode` DATETIME CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '0000:00:00 00:00:00';
Gravar "NULL" no campo Date, não está dando certo.Lembrando que data zerada não é padrão em SQL.
Se o MySQL estiver com STRICT MODE ativado também não aceita data zerada.
O padrão pra qualquer campo sem nada é NULL, que equivaleria ao NIL do Clipper/Harbour.
Assim da certo
INSERT INTO CLIENTES(IDCLI_COD,CLI_NOME,CLI_NASCEU) VALUES (2000,"JOAO","0000:00:00");
Assim da erro
INSERT INTO CLIENTES(IDCLI_COD,CLI_NOME,CLI_NASCEU) VALUES (2000,"JOAO","NULL");
ERROR 1292 (22007): Incorrect date value: 'NULL' form column 'CLI_NASCEU' at row 1
DESCRIBE CLIENTES;
Field Type Null Default
CLI_NASCEU Date YES NULL
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Não é "NULL", é NULL
A função pode ser usada na montagem do comando, por isso retorna como texto.
"INSERT INTO CLIENTES(IDCLI_COD,CLI_NOME,CLI_NASCEU) VALUES (2000,"JOAO"," + DateSql( mCli_Nasceu ) + ")"
Mas pra facilitar "enxergar" os comandos, acabei criando uma função/classe.
Até que acaba meio parecido com REPLACE cCampo WITH xConteudo
Mas facilita enxergar os "pares" de variável e conteúdo.
O mesmo pra UPDATE.
A função pode ser usada na montagem do comando, por isso retorna como texto.
"INSERT INTO CLIENTES(IDCLI_COD,CLI_NOME,CLI_NASCEU) VALUES (2000,"JOAO"," + DateSql( mCli_Nasceu ) + ")"
Mas pra facilitar "enxergar" os comandos, acabei criando uma função/classe.
Código: Selecionar todos
:QueryCreate()
:QueryAdd( "IDCLI_COD", nCodigo )
:QueryAdd( "CLI_NOME", cNome )
:QueryAdd( "CLI_NASCEU", dData )
:QueryExecuteInsert( "CLIENTES" )
Mas facilita enxergar os "pares" de variável e conteúdo.
O mesmo pra UPDATE.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Se interessar, a montagem de INSERT e UPDATE a partir do array aqui:
https://github.com/JoseQuintas/JoseQuin ... L566,#L606
https://github.com/JoseQuintas/JoseQuin ... L566,#L606
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- Itamar M. Lins Jr.
- Administrador

- Mensagens: 7928
- Registrado em: 30 Mai 2007 11:31
- Localização: Ilheus Bahia
- Curtiu: 1 vez
Dúvida inserir data no MySql
Ola!
Esta função nova para data que o Przemek criou facilita mais ainda.
Mude para:
Um picture para datas!
Já havia comentado em outro post mais antigo sobre essa possibilidade de alteração da gravação "default" da data no MySQL.
Saudações,
Itamar M. Lins Jr.
Esta função nova para data que o Przemek criou facilita mais ainda.
Código: Selecionar todos
cString := StrZero( Year( dDate ), 4 ) + "-" + StrZero( Month( dDate ), 2 ) + "-" + StrZero( Day( dDate ), 2 )Código: Selecionar todos
cString :=hb_dtoc(dDate,"yyyy-mm-dd") Código: Selecionar todos
* harbour/source/rtl/dateshb.c
+ added new .prg functions to mange date and timestamp values:
HB_DATETIME() -> <tTimeStamp>
HB_CTOD( <cDate> [, <cDateFormat> ] ) -> <dDate>
HB_DTOC( <dDate> [, <cDateFormat> ] ) -> <cDate>
HB_NTOT( <nValue> ) -> <tTimeStamp>
HB_TTON( <tTimeStamp> ) -> <nValue>
HB_TTOC( <tTimeStamp>, [ <cDateFormat> ] [, <cTimeFormat> ] ) ->
<cTimeStamp>
HB_CTOT( <cTimeStamp>, [ <cDateFormat> ] [, <cTimeFormat> ] ) ->
<tTimeStamp>
HB_TTOS( <tTimeStamp> ) -> <cYYYYMMDDHHMMSSFFF>
HB_STOT( <cDateTime> ) -> <tTimeStamp>
<cDateTime> should be in one of the above form:
- "YYYYMMDDHHMMSSFFF"
- "YYYYMMDDHHMMSSFF"
- "YYYYMMDDHHMMSSF"
- "YYYYMMDDHHMMSS"
- "YYYYMMDDHHMM"
- "YYYYMMDDHH"
- "YYYYMMDD"
- "HHMMSSFFF"
- "HHMMSSF"
- "HHMMSS"
- "HHMM"
- "HH"
Important is number of digits.
HB_TSTOSTR( <tTimeStamp> [, <lShorten> ] ) -> <cTimeStamp> // YYYY-MM-DD HH:MM:SS.fff
HB_STRTOTS( <cTimeStamp> ) -> <tTimeStamp>
<cTimeStamp> should be in one of the above form:
YYYY-MM-DD [H[H][:M[M][:S[S][.f[f[f[f]]]]]]] [PM|AM]
YYYY-MM-DDT[H[H][:M[M][:S[S][.f[f[f[f]]]]]]] [PM|AM]
The folowing characters can be used as date delimiters: "-", "/", "."
T - is literal "T" - it's for XML timestamp format
if PM or AM is used HH is in range < 1 : 12 > otherwise
in range < 0 : 23 >
HB_HOUR( <tTimeStamp> ) -> <nHour>
HB_MINUTE( <tTimeStamp> ) -> <nMinute>
HB_SEC( <tTimeStamp> ) -> <nSeconds> // with milliseconds
* harbour/source/rtl/datec.c
+ accept timestamp parameters in CMONTH() and CDOW() functions
* harbour/source/rtl/empty.c
+ added support for timestamp items
Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Itamar M. Lins Jr.
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Código: Selecionar todos
PROCEDURE Main
LOCAL d
d := Ctod("")
? hb_Dtoc( d, "YYYY-MM-DD" )
? hb_Dtoc( Date(), "YYYY-MM-DD" )
RETURN
Como usei DateSql(), vai acabar sendo só uma linha no aplicativo inteiro.- -
2017-08-15
Mas vou revisar se faço uso em outros lugares, de algo parecido.
De qualquer forma, data vazia continua precisando de ajuste.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Poderia ser assim também:
Transform( Dtos( Date() ), "@R 9999-99-99" )
Transform( Dtos( Date() ), "@R 9999-99-99" )
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Achei outro uso, no arquivo CNAB.
Neste seria difícil um equivalente a não se o hb_Dtoc() mesmo.
?? StrZero( Day( jpfinan->fiDatEmi ), 2 ) + StrZero( Month( jpfinan->fiDatEmi ), 2 ) + StrZero( Year( jpfinan->fiDatEmi ) - 2000, 2 )
?? hb_Dtoc( jpfinan->fiDatEmi, "DDMMYY" )
Neste seria difícil um equivalente a não se o hb_Dtoc() mesmo.
?? StrZero( Day( jpfinan->fiDatEmi ), 2 ) + StrZero( Month( jpfinan->fiDatEmi ), 2 ) + StrZero( Year( jpfinan->fiDatEmi ) - 2000, 2 )
?? hb_Dtoc( jpfinan->fiDatEmi, "DDMMYY" )
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- Itamar M. Lins Jr.
- Administrador

- Mensagens: 7928
- Registrado em: 30 Mai 2007 11:31
- Localização: Ilheus Bahia
- Curtiu: 1 vez
Dúvida inserir data no MySql
Ola!
Melhor configurar direto no Mysql, entretanto se a data estiver vazia e quer zeros:
Saudações,
Itamar M. Lins Jr.
Melhor configurar direto no Mysql, entretanto se a data estiver vazia e quer zeros:
Código: Selecionar todos
? STRTRAN( hb_Dtoc( ctod(""), "YYYY-MM-DD" )," ","0")Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Itamar M. Lins Jr.
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Mas acho interessante como eu fiz, criar uma DateSql() ou ValueSql() pra tudo.
Quem usa comando SQL vai usar muito isso, então mais prático chamar uma única função.
E já acerta do jeito que quiser nessa função (NULL ou '0000-00-00')
Eu só acho interessante usar NULL porque vale pra TUDO: SQL Server, Access, MySQL, Excel, etc., até mesmo ADS (DBF).
Não precisa se preocupar ao trocar a base de dados.
E vale pra base de dados que tenha sido criada em outro aplicativo - tem essa também.
Quem usa comando SQL vai usar muito isso, então mais prático chamar uma única função.
E já acerta do jeito que quiser nessa função (NULL ou '0000-00-00')
Eu só acho interessante usar NULL porque vale pra TUDO: SQL Server, Access, MySQL, Excel, etc., até mesmo ADS (DBF).
Não precisa se preocupar ao trocar a base de dados.
E vale pra base de dados que tenha sido criada em outro aplicativo - tem essa também.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Mas hb_Dtoc() foi muito interessante, aqui só no "fonte público".
https://github.com/JoseQuintas/JoseQuin ... bf3e2d58e0
https://github.com/JoseQuintas/JoseQuin ... bf3e2d58e0
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
- JoséQuintas
- Administrador

- Mensagens: 20267
- Registrado em: 26 Fev 2007 11:59
- Localização: São Paulo-SP
Dúvida inserir data no MySql
Lembrei da função inversa, pena que não funciona do mesmo jeito.
Código: Selecionar todos
PROCEDURE Main
? hb_Ctod( "20170815", "YYYYMMDD" )
? hb_Ctod( "15082017", "DDMMYYYY" )
? hb_Ctod( "2017-08-15", "YYYY-MM-DD" )
? hb_Ctod( "15-08-2017", "DD-MM-YYYY" )
RETURN
/ /
/ /
08/15/17
08/15/17
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"
https://github.com/JoseQuintas/
