elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  INSERT mysql, python y mysql.connector
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: INSERT mysql, python y mysql.connector  (Leído 2,485 veces)
hikki

Desconectado Desconectado

Mensajes: 4


Ver Perfil
INSERT mysql, python y mysql.connector
« en: 6 Octubre 2015, 03:52 am »

Hola, estoy teniendo unos problemas con este script haaa, estoy intentando escribir un algoritmo que actualice mi sitio web, pero tengo algunos problemas con el insert del mysql, aquí está el código:

Código
  1. #! python3
  2. # Just a test with mysqldb
  3.  
  4. import sys
  5. import mysql.connector
  6. from datetime import date, datetime, timedelta
  7.  
  8. def main():
  9.    db = mysql.connector.connect(user='', password='',
  10.                                 host='localhost',
  11.                                 database='')
  12.    cursor = db.cursor()
  13.  
  14.    now_date = datetime.now().date()
  15.  
  16.    cursor.execute("INSERT INTO games (name, description, url, category_id, category_parent, width, height, image, published, filetype, instructions, date_added, advert_id, highscores, mochi_id, seo_url, submitter)\
  17.        VALUES ('Tesla', 'this is just a description', 'http://juego..swf', 2, 0, 480, 248, 'http://localhsot.jpg', 0, 'swf', 'This are the instructions', %(now_date)s, 1, 1, '', 'some-game', 0)")
  18.  
  19.    db.close()
  20.  
  21. if '__main__' == __name__:
  22.    sys.exit(main())

Pero al correrlo me manda este error:
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(now_date)s, 1, 1, '', 'some-game', 0)' at line 1


En línea

0roch1

Desconectado Desconectado

Mensajes: 123



Ver Perfil
Re: INSERT mysql, python y mysql.connector
« Respuesta #1 en: 6 Octubre 2015, 21:41 pm »

Hola.

Te hace falta indicar el valor del parámetro now_date.

Tienes varias formas.

Código
  1. query = "INSERT INTO games (name, description, url, category_id, category_parent, width, height, image, published, filetype, instructions, date_added, advert_id, highscores, mochi_id, seo_url, submitter)\
  2.    VALUES ('Tesla', 'this is just a description', 'http://juego..swf', 2, 0, 480, 248, 'http://localhsot.jpg', 0, 'swf', 'This are the instructions', '%(date)s', 1, 1, '', 'some-game', 0)" % {'date': now_date}
  3.  
  4. cursor.execute(query)
  5.  

Otra forma
Código
  1. query = "INSERT INTO games (name, description, url, category_id, category_parent, width, height, image, published, filetype, instructions, date_added, advert_id, highscores, mochi_id, seo_url, submitter)\
  2.    VALUES ('Tesla', 'this is just a description', 'http://juego..swf', 2, 0, 480, 248, 'http://localhsot.jpg', 0, 'swf', 'This are the instructions', '"+ now_date.strftime('%Y-%m-%d') +"', 1, 1, '', 'some-game', 0)"
  3.  
  4. cursor.execute(query)
  5.  

Otra más
Código
  1. query = "INSERT INTO games (name, description, url, category_id, category_parent, width, height, image, published, filetype, instructions, date_added, advert_id, highscores, mochi_id, seo_url, submitter)\
  2.    VALUES ('Tesla', 'this is just a description', 'http://juego..swf', 2, 0, 480, 248, 'http://localhsot.jpg', 0, 'swf', 'This are the instructions', '"+ str(now_date) +"', 1, 1, '', 'some-game', 0)"
  3.  
  4. cursor.execute(query)
  5.  

Con la función NOW() de MySQL
Código
  1. query = "INSERT INTO games (name, description, url, category_id, category_parent, width, height, image, published, filetype, instructions, date_added, advert_id, highscores, mochi_id, seo_url, submitter)\
  2.    VALUES ('Tesla', 'this is just a description', 'http://juego..swf', 2, 0, 480, 248, 'http://localhsot.jpg', 0, 'swf', 'This are the instructions', NOW(), 1, 1, '', 'some-game', 0)"
  3.  
  4. cursor.execute(query)
  5.  
Este último utiliza la función de mysql, así que toma la fecha del servidor en donde se encuentre el SMBD.

No olvides hacer el commit para completar la transacción
Código
  1. cursor.execute(query)
  2.  
  3. db.commit()
  4.  
  5. db.close()
  6.  


En línea

hikki

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: INSERT mysql, python y mysql.connector
« Respuesta #2 en: 7 Octubre 2015, 21:59 pm »

Hola.

Te hace falta indicar el valor del parámetro now_date.

Tienes varias formas.


Gracias por la respuesta, pero ya encontré el error, execute() toma dos parámetros y sólo estaba pasando uno, el código ahora está así y funciona, también agregué el commit, gracias por

Código
  1. #! python3
  2. # trying to connect to mysql
  3.  
  4. import sys
  5. import mysql.connector
  6. import time
  7.  
  8. def main():
  9.    db = mysql.connector.connect(user='user', password='password',
  10.                                 host='localhost',
  11.                                 database='new_games')
  12.    cursor = db.cursor()
  13.  
  14.    query = ("INSERT INTO games (name, date_added) VALUES (%s, %s)")
  15.    data_games = ('Cyborg SpaceNow', time.strftime("%Y-%m-%d %H:%M:%S"))
  16.    cursor.execute(query, data_games)
  17.  
  18.    db.commit()
  19.  
  20.    cursor.close()
  21.    db.close()
  22.  
  23. if '__main__' == __name__:
  24.    sys.exit(main())
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Agregar MySQL Connector/ODBC 3.51 al proyecto
Programación Visual Basic
ReViJa 2 6,207 Último mensaje 28 Febrero 2011, 01:43 am
por raul338
¿Donde poner mysql-connector-java?
Java
Edersanluck 7 25,460 Último mensaje 15 Abril 2009, 20:21 pm
por celestino
Problema Con Python+Mysql (insert)
Scripting
b0h 2 3,675 Último mensaje 16 Marzo 2008, 16:26 pm
por b0h
Crear Instalador de Mi Programa y MySQL OBDC Connector
Programación Visual Basic
Rudy21 6 8,880 Último mensaje 12 Noviembre 2008, 02:40 am
por seba123neo
[AYUDA] ¿Como conecto Python con Mysql?
Scripting
bdred 1 2,563 Último mensaje 4 Abril 2018, 15:04 pm
por engel lex
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines