Foro de elhacker.net

Programación => Scripting => Mensaje iniciado por: hikki en 6 Octubre 2015, 03:52 am



Título: INSERT mysql, python y mysql.connector
Publicado por: hikki 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


Título: Re: INSERT mysql, python y mysql.connector
Publicado por: 0roch1 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.  


Título: Re: INSERT mysql, python y mysql.connector
Publicado por: hikki 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())