Good day to all!

What we have:

  1. Python 2.7
  2. Script to create a database

What do you need:

  1. I can create a new database (sqlite3) directly in the Python code, I specify it, I can connect to the ones created via sqlite3.connect() , and the Internet is full of similar examples.
  2. Run the existing script in it, which will create all the labels, etc. etc. The problem with the script is the following: in all examples of working with the database that I encountered using cursor.execute (Query text), the execute method does not allow to execute batch queries, i.e. one request is one action, the script does not run

Well, Python experts, I hope for your help.

ZY Thanks in advance for responding!

    3 answers 3

    1. sqlite3.connect()
    2. Cursor.executescript(sql_script).

    Example:

     import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table person( firstname, lastname, age ); create table book( title, author, published ); insert into book(title, author, published) values ( 'Dirk Gently''s Holistic Detective Agency', 'Douglas Adams', 1987 ); """) 
    • Thank you very much. The only question is: If the base already exists, then when you call connect (), the connection will be made and there will already be tables in it, and they will not be re-created by the script, how can you get around this, or just delete them with queries? - Sergey041691
    • one
      You might like this syntax CREATE TABLE IF NOT EXISTS tbl (...); he will create a table if there is none. And if the table is there, then nothing bad will happen. - KoVadim
    • And do not tell me how to save the database created in this way sqlite3.connect (": memory:")? I mean in the form of a file on the hard disk. - Sergey041691

    sqlite3.connect () will create a database if there is none.

      To save the base to a file, you need to use

       connection = sqlite3.connect('name.db') 

      Then the cursor:

       cursor = connection.cursor() 

      Then executescript('any script') . In this case, re-accessing the database named sqlite.connect('name.db') will only create a connection, but not a new database (if you come from other files, for example, knock on it). At the end of connection.close() .