Outils pour utilisateurs

Outils du site


issue55:tutopython

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
issue55:tutopython [2012/01/21 19:37] fredphil91issue55:tutopython [2012/01/30 21:50] (Version actuelle) fredphil91
Ligne 5: Ligne 5:
 Let's start by looking at the MySQL dump file. It consists of a section that creates the database, and then sections that create each table within the database followed by the data for that table, if it's included in the dump file. (There's an option to export the table schema(s) only). Shown above right is an example of one of the create table sections.** Let's start by looking at the MySQL dump file. It consists of a section that creates the database, and then sections that create each table within the database followed by the data for that table, if it's included in the dump file. (There's an option to export the table schema(s) only). Shown above right is an example of one of the create table sections.**
  
-Il y a quelques temps, on m'a demandé de convertir une base de données MySQL en SQLite. En cherchant une solution rapide et facile (et gratuite) sur internet, je n'ai rien trouvé qui fonctionnait pour moi avec la version actuelle de MySQL. Alors j'ai décidé d'aller de l'avant et de fabriquer ma solution moi-même.+Il y a quelque temps, on m'a demandé de convertir une base de données MySQL en SQLite. En cherchant une solution rapide et facile (et gratuite) sur internet, je n'ai rien trouvé qui fonctionnait pour moi avec la version actuelle de MySQL. Alors j'ai décidé d'aller de l'avant et de fabriquer ma solution moi-même.
  
-Le programme MySQL Administrator vous permet de sauvegarder une base de données dans un fichier texte à plat. Beaucoup de navigateurs SQLite vous permettent de lire un fichier SQL de définition à plat et de créer la base de données à partir de là. Cependant, il y a beaucoup de choses que MySQL supporte mais pas SQLite. Alors ce mois-ci, nous allons écrire un programme de conversion qui lit un fichier de « dump » (sauvegarde) MySQL et crée une version SQLite.+Le programme MySQL Administrator vous permet de sauvegarder une base de données dans un fichier texte à plat. Beaucoup de navigateurs SQLite vous permettent de lire un fichier SQL de définition à plat et de créer la base de données à partir de là. Cependant, il y a beaucoup de choses que MySQL supportemais pas SQLite. Alors ce mois-ci, nous allons écrire un programme de conversion qui lit un fichier de « dump » (sauvegarde) MySQL et crée une version SQLite.
  
-Commençons par regarder le fichier de « dump » MySQL. Il se compose d'une section qui crée la base de données, puis  des sections qui créent chaque table dans la base et insèrent des données dans ces tables, si les données sont contenues dans le fichier de « dump ». (Il existe une option pour exporter seulement les schémas des tables). Ci-dessus à droite se trouve un exemple d'une des sections de création de table.+Commençons par regarder le fichier de « dump » MySQL. Il se compose d'une section qui crée la base de données, puis  des sections qui créent chaque table dans la base et insèrent des données dans ces tables, si les données sont contenues dans le fichier de « dump ». (Il existe une option pour exporter seulement les schémas des tables.Ci-dessus à droite se trouve un exemple d'une des sections de création de table.
  
 **The first thing that we would need to get rid of is in the last line. Everything after the ending parenthesis needs to go away. (SQLite does not support an InnoDB database). In addition to that, SQLite doesn't support the “PRIMARY KEY” line. In SQLite, we set a primary key by using “INTEGER PRIMARY KEY AUTOINCREMENT” when we define the field. The other thing that SQLite doesn't support is the “unsigned” keyword. **The first thing that we would need to get rid of is in the last line. Everything after the ending parenthesis needs to go away. (SQLite does not support an InnoDB database). In addition to that, SQLite doesn't support the “PRIMARY KEY” line. In SQLite, we set a primary key by using “INTEGER PRIMARY KEY AUTOINCREMENT” when we define the field. The other thing that SQLite doesn't support is the “unsigned” keyword.
Ligne 21: Ligne 21:
 Quant aux données, les déclarations « INSERT INTO » sont également non-compatibles. Le problème ici est que SQLite ne permet pas les insertions multiples dans une même déclaration. Voici un court exemple tiré du fichier de « dump » MySQL. Remarquez (à droite) que le marqueur de fin de ligne est un point-virgule. Quant aux données, les déclarations « INSERT INTO » sont également non-compatibles. Le problème ici est que SQLite ne permet pas les insertions multiples dans une même déclaration. Voici un court exemple tiré du fichier de « dump » MySQL. Remarquez (à droite) que le marqueur de fin de ligne est un point-virgule.
  
-Nous allons également ignorer toutes les lignes de commentaireset les instructions « CREATE DATABASE » et « USE ». Une fois que nous aurons le fichier SQL converti, nous utiliserons un programme semblable à SQLite Database Browser qui est dans le domaine publique pour réellement créer la base de données, les tables et les données.+Nous allons également ignorer toutes les lignes de commentaires et les instructions « CREATE DATABASE » et « USE ». Une fois que nous aurons le fichier SQL converti, nous utiliserons un programme semblable à SQLite Database Browser qui est dans le domaine public, pour réellement créer la base de données, les tables et les données.
  
 **Let's get started. Start a new project folder and a new python file. Name it MySQL2SQLite.py. **Let's get started. Start a new project folder and a new python file. Name it MySQL2SQLite.py.
Ligne 37: Ligne 37:
 Commençons. Ouvrez un dossier pour ce nouveau projet et un nouveau fichier python. Nommez-le MonSQLversSQLite.py. Commençons. Ouvrez un dossier pour ce nouveau projet et un nouveau fichier python. Nommez-le MonSQLversSQLite.py.
  
-Vous voyez ci-dessus à droite la déclaration d'importation, la définition de classeet la routine <nowiki>__init__</nowiki>.+Vous voyez ci-dessus à droite la déclaration d'importation, la définition de classe et la routine <nowiki>__init__</nowiki>.
  
-Ce programme sera exécuté en ligne de commande, nous avons donc besoin de créer la déclaration « if <nowiki>__name__</nowiki> », un gestionnaire pour les arguments de ligne de commandeet une routine d'utilisation (si l'utilisateur ne sait pas comment utiliser le programme). Tout cela va tout à la fin du programme. Tout le reste du code se trouvera avant ceci :+Ce programme sera exécuté en ligne de commande, nous avons donc besoin de créer la déclaration « if <nowiki>__name__</nowiki> », un gestionnaire pour les arguments de ligne de commande et une routine d'utilisation (si l'utilisateur ne sait pas comment utiliser le programme). Tout cela va à la toute fin du programme. Tout le reste du code se trouvera avant ceci :
  
   def erreur(message):   def erreur(message):
Ligne 54: Ligne 54:
 where “Foo” is the name of the MySQL dump file, and “Bar” is the name of the SQLite sql file we want the program to create.** where “Foo” is the name of the MySQL dump file, and “Bar” is the name of the SQLite sql file we want the program to create.**
  
-La routine FaitLe() est appelée si notre programme est lancé à partir de la ligne de commande, ce pour quoi il est conçu. Cependant, si nous voulons pouvoir en faire une bibliothèque qui sera incluse dans un autre programme à un autre moment, nous pouvons simplement utiliser la classe. Ici nous avons mis en place un certain nombre de variables pour s'assurer que tout fonctionne correctement. Le code visible en bas à droite analyse ensuite les arguments de ligne de commande passés à notre programmeet prépare les choses pour les routines principales.+La routine FaitLe() est appelée si notre programme est lancé à partir de la ligne de commande, ce pourquoi il est conçu. Cependant, si nous voulons pouvoir en faire une bibliothèque qui sera incluse dans un autre programme à un autre moment, nous pouvons simplement utiliser la classe. Ici nous avons mis en place un certain nombre de variables pour s'assurer que tout fonctionne correctement. Le code visible en bas à droite analyse ensuite les arguments de ligne de commande passés à notre programme et prépare les choses pour les routines principales.
  
-Quand nous commençons le programme, nous devons fournir au moins deux variables sur la ligne de commande. Ce sont les fichiers d'entrée et de sortie. Nous fournirons également une information pour permettre à l'utilisateur de voir ce qui se passe pendant que le programme est lancé, une option pour simplement créer les tables et de ne pas charger les donnéeset un moyen pour l'utilisateur d'appeler au secours. La ligne de commande « normale » pour démarrer le programme ressemble à ceci :+Quand nous commençons le programme, nous devons fournir au moins deux variables sur la ligne de commande. Ce sont les fichiers d'entrée et de sortie. Nous fournirons également une information pour permettre à l'utilisateur de voir ce qui se passe pendant que le programme est lancé, une option pour simplement créer les tablesne pas charger les données et un moyen pour l'utilisateur d'appeler au secours. La ligne de commande « normale » pour démarrer le programme ressemble à ceci :
  
 MonSQLversSQLite FicEntree=Foo FicSortie=Bar MonSQLversSQLite FicEntree=Foo FicSortie=Bar
Ligne 62: Ligne 62:
 où « Foo » est le nom du fichier de dump MySQL, et « Bar » est le nom du fichier SQLite que le programme doit créer. où « Foo » est le nom du fichier de dump MySQL, et « Bar » est le nom du fichier SQLite que le programme doit créer.
  
-You can also call it like this:+**You can also call it like this:
  
 MySQL2SQLite Infile=Foo Outfile=Bar Debug SchemaOnly MySQL2SQLite Infile=Foo Outfile=Bar Debug SchemaOnly
Ligne 70: Ligne 70:
 Finally if the user asks for help, we just go to the usage portion of the program. Finally if the user asks for help, we just go to the usage portion of the program.
  
-Before we continue, let's take another look at how the command line argument support works.+Before we continue, let's take another look at how the command line argument support works.**
  
-When a user enters the program name from the command line (terminal), the operating system keeps track of the information entered and passes it to the program just in case there are any options entered. If no options (also called arguments) are entered, the number of arguments is one, which is the name of the application - in our case MySQL2SQLite.py. We can access these arguments by calling the sys.arg command. If the count is greater than one, we will access them in a for loop. We will step through the list of arguments and check each one. Some programs require you to enter the arguments in a specific order. By using the for loop approach, the arguments can be entered in any order. If the user doesn't supply any arguments, or uses the help arguments, we show the usage screen. Shown above is the routine for that.+Vous pouvez également l'appeler ainsi :
  
-Moving on, once we have parsed the argument set, we instantiate the class, call the setup routine, which fills certain variables and then call the DoWork routine. We'll start our class now (which is shown on the next page, bottom right).+MonSQLversSQLite FicEntree=Foo FicSortie=Bar Debug SchemaSeulement
  
-This (next page, top right) is the definition and the __init__ routine. Here we setup the variables that we will need as we go through the code. Remember that right before we call the DoWork routine, we call the Setup routine. We take our empty variables and assign the correct values to them here. Notice that there is the ability to not write to a file, useful for debugging purposes. We also have the ability to simply write the schema, or database structure, without writing the data. This is helpful if you are taking a database and starting a new project without wanting to use any existing data.+ce qui ajoutera l'option pour afficher les messages de débogage et pour créer SEULEMENT les tables sans importer les données.
  
-We start off by opening the SQL Dump filethen setting some internal scope variables. We also define some strings to save us typing later on. Then, if we are to write to an output file, we open it and then we start the entire process. We will read each line of the input file, process it, and potentially write it to the output file. We use a forced while loop to assist reading each line, with a break command when there is nothing left in the input file. We use f.readline() to get the line to work, and assign it to the variable “line”. Some lines, we can safely ignore. We'll simply use an if/elif statement followed by a pass statement to accomplish this (below).+Finalement si l'utilisateur demande de l'aide, on va simplement dans la section « Utilisation » du programme.
  
-Next we can stop ignoring things and actually do something. If we have a CreateTable statement, we'll start that process. Remember we defined CT to be equal to “Create Table”. Here (above right), we set a variable “CreateTableMode” to be equal to 1, so we know that's what we are doing, since each field definition is on a separate line. We then take our line, remove the carriage return, and get that ready to write to our out file, and, if required, write it.+Avant de continuer, regardons à nouveau comment fonctionne la prise en charge des arguments de la ligne de commande. 
 + 
 +**When a user enters the program name from the command line (terminal), the operating system keeps track of the information entered and passes it to the program just in case there are any options entered. If no options (also called arguments) are entered, the number of arguments is one, which is the name of the application - in our case MySQL2SQLite.py. We can access these arguments by calling the sys.arg command. If the count is greater than one, we will access them in a for loop. We will step through the list of arguments and check each one. Some programs require you to enter the arguments in a specific order. By using the for loop approach, the arguments can be entered in any order. If the user doesn't supply any arguments, or uses the help arguments, we show the usage screen. Shown above is the routine for that. 
 + 
 +Moving on, once we have parsed the argument set, we instantiate the class, call the setup routine, which fills certain variables and then call the DoWork routine. We'll start our class now (which is shown on the next page, bottom right).** 
 + 
 +Lorsqu'un utilisateur entre le nom du programme en ligne de commande (terminal), le système d'exploitation conserve la trace des informations saisies et il les passe au programme juste au cas où des options ont été saisies. Si aucune option (autrement nommée argument) n'est saisie, le nombre d'arguments est un, ce qui correspond au nom de l'application - dans notre cas, MonSQLversSQLite.py. On accède à ces arguments avec la commande sys.arg. Si le nombre est supérieur à un, nous allons utiliser une boucle for pour y accéder. Nous allons parcourir la liste des arguments et vérifier chacun d'eux. Certains programmes exigent que vous entriez les arguments dans un ordre précis. En utilisant l'approche avec une boucle for, les arguments peuvent être saisis dans n'importe quel ordre. Si l'utilisateur ne fournit pas d'argument, ou utilise l'un des arguments d'aide, on affiche l'écran d'utilisation. Ci-dessus se trouve la routine pour cela. 
 + 
 +Ensuite, une fois que nous avons analysé l'ensemble des arguments, nous instancions la classe, appelons la routine de configuration qui remplit certaines variables et ensuite appelons la routine ExecuterTravail. Nous allons commencer notre classe maintenant (voir en bas à droite de la page suivante). 
 + 
 +**This (next page, top right) is the definition and the <nowiki>__init__</nowiki> routine. Here we setup the variables that we will need as we go through the code. Remember that right before we call the DoWork routine, we call the Setup routine. We take our empty variables and assign the correct values to them here. Notice that there is the ability to not write to a file, useful for debugging purposes. We also have the ability to simply write the schema, or database structure, without writing the data. This is helpful if you are taking a database and starting a new project without wanting to use any existing data. 
 + 
 +We start off by opening the SQL Dump file, then setting some internal scope variables. We also define some strings to save us typing later on. Then, if we are to write to an output file, we open it and then we start the entire process. We will read each line of the input file, process it, and potentially write it to the output file. We use a forced while loop to assist reading each line, with a break command when there is nothing left in the input file. We use f.readline() to get the line to work, and assign it to the variable “line”. Some lines, we can safely ignore. We'll simply use an if/elif statement followed by a pass statement to accomplish this (below).** 
 + 
 +Voici (page suivante, en haut à droite) les configurations et la routine <nowiki>__init__</nowiki>. Ici, nous configurons les variables dont nous aurons besoin tout au long du code. Souvenez-vous que juste avant d'appeler la routine ExecuterTravail, nous appelons la routine de configuration, où nous prendrons les variables vides pour leur assigner des valeurs correctes. Notez qu'on laisse la possibilité de ne pas écrire dans un fichier, ce qui est utile pour le débogage. Nous avons également la possibilité de simplement écrire le schéma (la structure de la base de données), sans écrire les données. Ceci est utile si vous prenez une base de données et commencez un nouveau projet sans vouloir utiliser des données existantes. 
 + 
 +Nous commençons par ouvrir le fichier de dump SQL, puis nous définissons les variables à portée interne. Nous définissons aussi certaines chaînes pour nous éviter de les saisir plus tard. Ensuite, si nous prévoyons d'écrire un fichier de sortie, nous l'ouvrons puis nous commençons le processus complet. Nous lirons chaque ligne du fichier d'entrée, pour les traiter et éventuellement, les écrire dans le fichier de sortie. Nous utilisons une boucle while infinie pour la lecture des lignes, avec une commande « break » quand il ne reste rien dans le fichier d'entrée. Nous utilisons f.readline() pour obtenir la ligne à convertir et nous l'assignons à la variable « ligne ». Certaines lignes peuvent être ignorées. Nous allons simplement utiliser une instruction if/elif suivie par une instruction pass pour cela (ci-dessous). 
 + 
 +**Next we can stop ignoring things and actually do something. If we have a CreateTable statement, we'll start that process. Remember we defined CT to be equal to “Create Table”. Here (above right), we set a variable “CreateTableMode” to be equal to 1, so we know that's what we are doing, since each field definition is on a separate line. We then take our line, remove the carriage return, and get that ready to write to our out file, and, if required, write it.
  
 Now (middle right) we need to start dealing with each line within the create table statements - manipulating each line to keep SQLite happy. There are many things that SQLite won't deal with. Let's look at a Create Table statement from MySQL again. Now (middle right) we need to start dealing with each line within the create table statements - manipulating each line to keep SQLite happy. There are many things that SQLite won't deal with. Let's look at a Create Table statement from MySQL again.
  
-One thing that SQLite will absolutely have an issue with is the entire last line after the closing parenthesis. Another is the line just above that, the Primary Key line. Yet another thing is the unsigned keyword in the second line. It will take a bit of code (below) to work around these issues, but we can make it happen.+One thing that SQLite will absolutely have an issue with is the entire last line after the closing parenthesis. Another is the line just above that, the Primary Key line. Yet another thing is the unsigned keyword in the second line. It will take a bit of code (below) to work around these issues, but we can make it happen.** 
 + 
 +Ensuite nous pouvons cesser d'ignorer les choses et faire agir pour de bon. Si nous rencontrons une déclaration CreateTable, nous allons commencer ce processus. Rappelez-vous, nous avons défini CT comme étant égal à "CREATE TABLE". Ici (en haut à droite), nous réglons une variable « ModeCreationTable » sur 1, pour savoir que c'est ce que nous faisons, car chaque définition de champ est sur une ligne distincte. Nous prenons ensuite notre ligne, supprimons le retour chariot, la préparons pour être écrite dans le fichier de sortie, et si nécessaire nous l'écrivons. 
 + 
 +Maintenant (à droite au milieu), nous devons commencer à traiter chaque ligne contenue dans l'instruction de création de table - en manipulant chaque ligne pour que SQLite soit content. Il y a plusieurs choses que SQLite ne traitera pas. Regardons une instruction CREATE TABLE MySQL à nouveau. 
 + 
 +Une chose qui va vraiment poser problème à SQLite est la toute dernière ligne après la parenthèse fermante. Une autre est la ligne juste au-dessus, la ligne de clé primaire. Une autre chose est le mot-clé unsigned à la deuxième ligne. Cela va nécessiter un peu de code (ci-dessous) pour contourner ces problèmes, mais nous pouvons y arriver.
  
-First, (third down on the right) we check to see if the line contains “auto increment”. We will assume that this will be the primary key line. While this might be true 98.6% of the time, it won't always be. However, we'll keep it simple. Next we check to see if the line starts with “) ”. This will signify this is the last line of the create table section. If so, we simply set a string to close the statement properly in the variable “newline”, turn off the CreateTableMode variable, and, if we are writing to file, write it out.+**First, (third down on the right) we check to see if the line contains “auto increment”. We will assume that this will be the primary key line. While this might be true 98.6% of the time, it won't always be. However, we'll keep it simple. Next we check to see if the line starts with “) ”. This will signify this is the last line of the create table section. If so, we simply set a string to close the statement properly in the variable “newline”, turn off the CreateTableMode variable, and, if we are writing to file, write it out.
  
 Now (bottom right) we use the information we found about the auto increment key word. First, we strip the line of any spurious spaces, then check to see where (we are assuming it is there) the phrase “ int(“ is within the line. We will be replacing this with the phrase “ INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL”. The length of the integer doesn't matter to SQLite. Again, we write it out if we should. Now (bottom right) we use the information we found about the auto increment key word. First, we strip the line of any spurious spaces, then check to see where (we are assuming it is there) the phrase “ int(“ is within the line. We will be replacing this with the phrase “ INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL”. The length of the integer doesn't matter to SQLite. Again, we write it out if we should.
Ligne 94: Ligne 118:
 elif line.strip().startswith(PK): elif line.strip().startswith(PK):
              
-    pass+    pass**
  
-Now (top right) we look for the phrase “ unsigned “ (again keep the extra spaces) and replace it with “ “.+Tout d'abord, (troisième cadre sur la droite), nous vérifions si la ligne contient « auto increment ». Nous supposerons que ce sera la ligne de clé primaire. Bien que cela soit vrai 98,6 % du temps, ça n'est pas toujours le cas. Cependant, nous allons garder les choses simples. Ensuite nous vérifions si la ligne commence par « ) ». Cela signifie que ceci est la dernière ligne de la section CREATE TABLE. Si oui, nous écrivons simplement une chaîne pour fermer correctement la déclaration dans la variable « nouvelleLigne », réglons la variable ModeCreationTable à 0 et, si nous écrivons dans un fichier, nous réalisons l'écriture. 
 + 
 +Maintenant (en bas à droite), nous utilisons les informations que nous avons trouvées sur le mot-clé auto incrément. Tout d'abord, nous enlevons de la ligne tous les espaces parasites, puis vérifions pour voir où se trouve (nous supposons qu'elle est là) l'expression « int( » dans la ligne. Nous la remplacerons par l'expression « INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ». la longueur de l'entier n'est pas importante pour SQLite. Encore une fois, nous l'écrivons si c'est nécessaire. 
 + 
 +Maintenant nous cherchons l'expression « PRIMARY KEY » dans la ligne. Remarquez l'espace supplémentaire à la fin - c'est exprès. Si on la trouve, on ignore la ligne. 
 + 
 +  elif line.strip().startswith(PK): 
 +          pass 
 + 
 +**Now (top right) we look for the phrase “ unsigned “ (again keep the extra spaces) and replace it with “ “.
  
 That's the end of the create table routine. Now (below) we move on to the insert statements for the data. The InsertStart variable is the phrase “INSERT INTO “. We check for that because MySQL allows for multiple insert statements in a single command, but SQLite does not. We need to make separate statements for each block of data. We set a variable called “insertmode” to 1, pull the “INSERT INTO {Table} {Fieldlist} VALUES (“ into a reusable variable (which I'll call our prelude), and move on. That's the end of the create table routine. Now (below) we move on to the insert statements for the data. The InsertStart variable is the phrase “INSERT INTO “. We check for that because MySQL allows for multiple insert statements in a single command, but SQLite does not. We need to make separate statements for each block of data. We set a variable called “insertmode” to 1, pull the “INSERT INTO {Table} {Fieldlist} VALUES (“ into a reusable variable (which I'll call our prelude), and move on.
Ligne 103: Ligne 136:
  
 elif self.SchemaOnly == 0: elif self.SchemaOnly == 0:
-   if insertmode == 1:+   if insertmode == 1:**
  
-We check to see if there is either “');” or “'),” in our line. In the case of “');”, this would be the last line in our insert statement set.+Maintenant (en haut à droitenous recherchons l'expression « unsigned » (encore une fois remarquez les espaces supplémentaireset la remplaçons par « ».
  
-posx = line.find("');"+C'est la fin de la routine de création de table. Maintenant (ci-dessous), nous passons aux requêtes d'insertion pour les données. La variable DebutInsertion contient l'expression « INSERT INTO ». Nous vérifions cela parce que MySQL permet d'insérer plusieurs déclarations en une seule commande, mais pas SQLite. Nous devons faire des déclarations distinctes pour chaque bloc de données. Nous réglons une variable appelée « ModeInsertion » à 1, plaçons le « INSERT INTO {table} {liste des champs} VALUES ( » dans une variable réutilisable (que je vais appeler notre prélude), et continuons. 
-pos1 = line.find("'),"+ 
-l1 = line[:pos1]+Maintenant, nous vérifions si nous devons seulement travailler sur le schéma. Si oui, nous pouvons ignorer sans problème toutes les instructions d'insertion. Sinon, nous devons nous en occuper. 
 + 
 +  elif self.SchemaSeulement == 0: 
 +    if ModeInsertion == 1: 
 + 
 +**We check to see if there is either “');” or “'),” in our line. In the case of “');”, this would be the last line in our insert statement set. 
 + 
 +  posx = line.find("');"
 +  pos1 = line.find("'),"
 +  l1 = line[:pos1]
  
 This line checks for escaped single quotes and replaces them. This line checks for escaped single quotes and replaces them.
  
-line = line.replace("\\'","''")+  line = line.replace("\\'","' '")
  
 If we have a closing statement (“);”), that is the end of our insert set, and we can create the statement by joining the prelude to the actual value statement. This is shown on the previous page, bottom right. If we have a closing statement (“);”), that is the end of our insert set, and we can create the statement by joining the prelude to the actual value statement. This is shown on the previous page, bottom right.
  
-This all works (top right) if the last value we have in the insert statement is a quoted string. However, if the last value is a numeric value, we have to deal with things a bit differently. You'll be able to pick out what we are doing here.+This all works (top right) if the last value we have in the insert statement is a quoted string. However, if the last value is a numeric value, we have to deal with things a bit differently. You'll be able to pick out what we are doing here.**
  
-Finally, we close our input file, and, if we are writing an output file, we close that as well.+Nous vérifions s'il y a soit « '); » soit « '), » dans notre ligne. Le cas « '); » indique que c'est la dernière ligne de l'ensemble d'instructions d'insertion. 
 + 
 +  posx = line.find ("');"
 +  pos1 = line.find ("'),"
 +  longueur1 = ligne[:pos1] 
 + 
 +Cette ligne vérifie s'il y a des apostrophes échappées et les remplace. 
 + 
 +  ligne = ligne.replace("\\'","''"
 + 
 +Si nous avons une déclaration de clôture (");"), c'est alors la fin de notre ensemble d'insertions et nous pouvons créer l'instruction en concaténant le prélude à l'instruction de valeur proprement dite. Ceci est illustré en bas à droite de la page précédente. 
 + 
 +Tout cela fonctionne (en haut à droite) si la dernière valeur que nous avons dans l'instruction INSERT est une chaîne entre guillemets. Cependant, si la dernière valeur est une valeur numérique, nous devons procéder un peu différemment. Vous serez en mesure de comprendre ce que nous faisons ici. 
 + 
 +**Finally, we close our input file, and, if we are writing an output file, we close that as well.
  
 f.close() f.close()
Ligne 131: Ligne 187:
 As always, the code is up at PasteBin at http://pastebin.com/cPvzNT7T. As always, the code is up at PasteBin at http://pastebin.com/cPvzNT7T.
  
-See you next time.+See you next time.** 
 + 
 +Enfin, nous fermons notre fichier d'entrée et, si nous écrivons un fichier de sortie, nous le fermons aussi. 
 + 
 +  f.close () 
 +  if self.EcrireFichier == 1: 
 +    FichierDest.close () 
 + 
 +Une fois que vous avez votre fichier converti, vous pouvez utiliser SQLite Database Browser pour remplir la structure de la base et les données. 
 + 
 +Ce code devrait fonctionner tel quel dans plus de 90 % des cas. Nous pourrions avoir oublié certaines choses à cause d'autres problèmes, c'est pour cela qu'un mode Debug est prévu. Cependant, j'ai testé cela sur plusieurs fichiers et n'ai eu aucun problème. 
 + 
 +Comme toujours, le code est disponible sur Pastebin : http://pastebin.com/Bdt64VqS. 
 + 
 +À la prochaine fois. 
issue55/tutopython.1327171021.txt.gz · Dernière modification : 2012/01/21 19:37 de fredphil91