2015-10-09 2 views
1

Я пытаюсь создать базу данных с помощью кода Genie. Однако я сталкиваюсь с проблемами с документацией, поэтому я прошу здесь!Создание таблицы в базе данных Sqlite с Genie?

Это можно считать неинтуитивным, потому что я могу запустить sqlite непосредственно в командной строке и создать набор данных. Я делаю это по диким причинам.

кода Я пытаюсь подражать в питоне:

#-------------------------------------- 
import apsw 
#-------------------------------------- 
# Opening/creating database. Database name is cookbook.db3 
connection=apsw.Connection("cookbook.db3") 
cursor=connection.cursor() 
#-------------------------------------- 
# Create The Tables 
#-------------------------------------- 
sql = 'CREATE TABLE Recipes (pkiD INTEGER PRIMARY KEY, name TEXT, servings TEXT, source TEXT)' 
cursor.execute(sql) 
sql = 'CREATE TABLE Instructions (pkID INTEGER PRIMARY KEY, instructions TEXT, recipeID NUMERIC)' 
cursor.execute(sql) 
sql = 'CREATE TABLE Ingredients (pkID INTEGER PRIMARY KEY, ingredients TEXT, recipeID NUMERIC)' 
cursor.execute(sql) 
#-------------------------------------- 
# Insert Data into tables 
#-------------------------------------- 
# Insert data into Recipe table 
sql = 'INSERT INTO Recipes (name,servings,source) VALUES ("Spanish Rice",4,"Greg")' 
cursor.execute(sql) 
# Get the pkid for the inserted record 
sql = "SELECT last_insert_rowid()" 
cursor.execute(sql) 
for x in cursor.execute(sql): 
    lastid = x[0] 
# Insert data into the instructions table 
sql = 'INSERT INTO Instructions (recipeID,instructions) VALUES(%s,"Brown hamburger. Stir in all other ingredients. Bring to a boil. Stir. Lower to simmer. Cover and cook for 20 minutes or until all liquid is absorbed.")' % lastid 
cursor.execute(sql) 
# Insert data into the ingredients table 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 cup parboiled Rice (uncooked)")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 pound Hamburger")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"2 cups Water")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 8 oz can Tomato Sauce")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 small Onion chopped")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 clove Garlic chopped")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 tablespoon Ground Cumin")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 teaspoon Ground Oregano")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"Salt and Pepper to taste")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"Salsa to taste")' % lastid 
cursor.execute(sql) 
# Put in one more for good "measure" 
sql = 'INSERT INTO Recipes (name,servings,source) VALUES ("Pickled Pepper-Onion Relish","9 half pints","Complete Guide to Home Canning")' 
cursor.execute(sql) 
# Get the pkid for the inserted record 
sql = "SELECT last_insert_rowid()" 
cursor.execute(sql) 
for x in cursor.execute(sql): 
    lastid = x[0] 
sql = 'INSERT INTO Instructions (recipeID,instructions) VALUES(%s,"Wash and chop vegetables. Combine all ingredients and boil gently until mixture thickens and volume is reduced by 1/2 (about 30 minutes). Fill sterile jars with hot relish, leaving 1/2 inch head space and seal tightly. Store in refrigerator and use within one month or process in boiling water bath if extended storage is desired. Hot pack process time at 0-1000 feet for 5 minutes, 1,001 to 6000 ft 10 minutes, above 6,000 ft 15 minutes.")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"6 cups finely chopped Onions")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"3 cups finely chopped Red Peppers")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"3 cups finely chopped Green Peppers")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"1 1/2 cups sugar")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"6 cups White Vinegar (5 percent)")' % lastid 
cursor.execute(sql) 
sql = 'INSERT INTO Ingredients (recipeID,ingredients) VALUES (%s,"2 tablespoons canning or pickling salt")' % lastid 
cursor.execute(sql) 
# Tell us we are done 
print 'Done' 

Я узнал, как использовать vala.doc, и я нашел рутину манипулировать SQLite базы данных: Sqlite.Database. Тем не менее, я продолжаю получать ошибку при компиляции.

Это как далеко я на воспроизводя этот код:

/* HOW TO CREATE THE DB WITH GENIE */ 

// Opening/creating db. 

[indent=4] 
init 
    Sqlite.Database db 
    string errmsg 

    int ec = Sqlite.Database.open("cookbook.db", out db) 
    if ec != Sqlite.OK 
     stderr.printf("Can't open database: %d: Ss\n", db.errcode(), db.errmesg) 
     return -1 

    // Insert data 
    query:string =""" 
     CREATE TABLE Recipes (pkiD INTEGER PRIMARY KEY, name TEXT, servings TEXT, source TEXT) 
     """ 
    db.exec (query, null, out errmsg) 

Он suposed для вставки таблицы в базе данных, но я получаю следующее сообщение об ошибке:

valac --pkg sqlite3 cookcreate.gs 
cookcreate.gs:9.11-9.11: error: syntax error, expected `:' but got `.' with previous identifier 
    Sqlite.Database db 
     ^
Compilation failed: 1 error(s), 0 warning(s) 

Любая помощь будем очень благодарны.

+0

Вашего кода не похоже Python..Where вы кодирования? –

+0

Вы имеете в виду первый? Это питон, и он работает. Кодирование по элементарным. Вы заметили, что я пытаюсь перевести его на язык программирования Genie, так? Это не SQL Genie. –

+0

Ohhh ryt ... my miss.let me проверить, могу ли я помочь. –

ответ

1

Похоже, что вы использовали этот пример в Valadoc, но не преобразовали информацию о типе из синтаксиса Vala в синтаксис Genie. Таким образом, Sqlite.Database db будет db:Sqlite.Database.

Работающий пример Genie будет:

[indent=4] 
init 
    db:Sqlite.Database 
    errmsg:string 

    ec:int = Sqlite.Database.open("cookbook.sqlite", out db) 
    if ec != Sqlite.OK 
     stderr.printf("Can't open database: %d: %s\n", db.errcode(), db.errmsg()) 
     Process.exit(-1) 

    query:string ="""CREATE TABLE Recipes (
     pkiD INTEGER PRIMARY KEY, 
     name TEXT, 
     servings TEXT, 
     source TEXT 
     ) 
    """ 
    db.exec (query, null, out errmsg) 

Пару вещей отметить:

  • Genie может вернуть только успешный результат, поэтому return -1 в настоящее время не допускается. Это может измениться в какой-то момент, см. https://bugzilla.gnome.org/show_bug.cgi?id=707233 Чтобы обойти это, вы можете использовать Process.exit() GLib, как используется в примере выше. Это имеет тот недостаток, что программа немедленно прекращается без разрушения объекта. Поэтому, если вы используете final в своих классах, чтобы закрыть соединение с базой данных, например, блок final не будет вызываться. Или вы можете просто return, который всегда возвращает 0
  • Стенограммы струны, """I'm a verbatim string""", отлично подходит для встраивания SQL в Genie :-)
+0

Спасибо, что заставило меня двигаться вперед. Но у меня возникли два новых вопроса: (i) строчная строка требует какой-либо конкретной идентификации между кавычками? –

+0

Конкретный отступ не требуется. То, что написано в строке verbatim, передается SQLite в формате, точно так же, как написано. Поскольку SQLite может справиться с этим, это нормально. В этом примере я использовал отступы, чтобы упростить чтение. – AlThomas

 Смежные вопросы

  • Нет связанных вопросов^_^