Menu

auto_increment in INSERT

Help
ee_lars
2008-01-10
2012-09-19
  • ee_lars

    ee_lars - 2008-01-10

    Hello,

    I'm writing a script which let inserting values from a csv file to a mysql database.

    here is a table of the database :

    create table association
    (id INT not null auto_increment,
    nom VARCHAR(100) not null,
    service VARCHAR (50) not null,
    theme VARCHAR (30) not null,
    PRIMARY KEY (id)
    )

    I've got a problem with the insert query :
    requete = "INSERT INTO association(id, nom, service, theme) VALUES (default, %s, %s, %s)", (default, nom, service, theme)

    At the execution of the script, i get the following error :

    File "importmysql.py", line 28, in <module>
    requete = "INSERT INTO association(id, nom, service, theme) VALUES (%s, %s, %s, %s)", (default, nom, service, theme)
    NameError: name 'default' is not defined

    I read in another thread of the forum that the value default is not necessary, so i removed it writing :
    requete = "INSERT INTO association(id, nom, service, theme) VALUES (, %s, %s, %s)", (nom, service, theme)

    Now i get : raise errorclass, errorvalue
    TypeError: query() argument 1 must be string or read-only buffer, not tuple

    I don't understand how to insert that damned 'id' value...

    Thanks by advance for any answer.

     
    • Kyle VanderBeek

      Kyle VanderBeek - 2008-01-10

      Just don't provide the name of the column, it will default to a the next auto_increment value.

      cursor.execute("INSERT INTO association (nom, service, theme) VALUES (%s, %s, %s)", (nom, service, theme))

      As a side note, I generally recommend against 2-letter generic column names like "id". Later you'll go insane trying to grep for all the places where "id" is used. :-)

       
    • ee_lars

      ee_lars - 2008-01-10

      Cool it works!!!
      I just use your syntax to get it working... thanks a lot.

      I retried with mine (putting the query in the variable 'requete') and i got the same error...
      Is it possible to execute queries stored in variables???

      ps : for the 'id' it was just a basic table constructed for a test, but thanks anyway for that advice :)

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.