2017-02-20 70 views
1

背景:SQLAlchemy的 - 簡單的SELECT語句

我很新的SQLAlchemy的,它似乎是爲我應該如何選擇的事情相當混亂。

我在我的MySQL數據庫被稱爲基因,在那裏我有gene_id,gene_description一個表,gene_symbol

我想要做什麼:

所有我想要做的是一個簡單的選擇查詢:

Select * from Genes 

但我似乎困惑,我們應如何做到這一點

這裏是我做了什麼:

import sqlalchemy 
from sqlalchemy.orm import sessionmaker 
from sqlalchemy.ext.automap import automap_base 
import csv 
import pandas as pd 

engine = sqlalchemy.create_engine('mysql://root:[email protected]') # connect to server 
metadata = sqlalchemy.MetaData(bind=engine) 
engine.execute("USE TestDB") 

genes = sqlalchemy.table('Genes') 
s = sqlalchemy.select([genes]) 
engine.execute(s) 

問題:

ProgrammingError: (_mysql_exceptions.ProgrammingError) (1064, "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 'FROM `Genes`' at line 2") [SQL: u'SELECT \nFROM `Genes`'] 

也有一些類型的 「智能感知」 在那裏我可以做類似gene_table = engine.Gene。如果我不誤,有一種方法與映射做到這一點,但它並沒有爲我工作

編輯: 這可能會幫助:

How to automatically reflect database to sqlalchemy declarative?

+1

沒有指定表中的任何行,所以發出的查詢有語法錯誤,由於空表達式列表。您應該定義列(手動或通過反射),或者,如果您確實需要'SELECT * ...',請執行select([「*」])。select_from(genes)'。 – univerio

回答

1

所以我們可以使用反射和不必須明確創建類,但如果我們想速度,我們可以使用類似sqlautocode創建它們如下所述:

Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?

也有是有問題MySQL數據庫它會給看起來像下面的錯誤:(從到位桶採取:https://bitbucket.org/zzzeek/sqlalchemy/issues/1909/reflection-issue-with-mysql-url-with-no

SNIP... 
File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/schema.py", line 1927, in __init__ 
    self.reflect() 
    File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/schema.py", line 2037, in reflect 
    connection=conn)) 
    File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/engine/base.py", line 1852, in table_names 
    return self.dialect.get_table_names(conn, schema) 
    File "<string>", line 1, in <lambda> 
    File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/engine/reflection.py", line 32, in cache 
    return fn(self, con, *args, **kw) 
    File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/dialects/mysql/base.py", line 1791, in get_table_names 
    self.identifier_preparer.quote_identifier(current_schema)) 
    File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/sql/compiler.py", line 1517, in quote_identifier 
    return self.initial_quote + self._escape_identifier(value) + self.final_quote 
    File "/opt/buildout-eggs/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/dialects/mysql/mysqldb.py", line 77, in _escape_identifier 
    value = value.replace(self.escape_quote, self.escape_to_quote) 
AttributeError: 'NoneType' object has no attribute 'replace' 

這是解決通過添加數據庫名稱(您正在使用的一個),如下所示:

engine = create_engine('mysql+mysqldb://USER_NAME:[email protected]/DATABASE_NAME', pool_recycle=3600) # connect to server 

我用這個正確連接: http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html 這: http://docs.sqlalchemy.org/en/latest/core/engines.html

這也可以幫助: How to automatically reflect database to sqlalchemy declarative?

我的代碼最後看起來像這樣:

from sqlalchemy.ext.automap import automap_base 
from sqlalchemy.orm import Session 
from sqlalchemy import create_engine 

Base = automap_base() 

# engine, suppose it has two tables 'user' and 'address' set up 
engine = create_engine('mysql+mysqldb://root:[email protected]/TestDB', pool_recycle=3600) # connect to server 

# reflect the tables 
Base.prepare(engine, reflect=True) 

# mapped classes are now created with names by default 
# matching that of the table name. 
Genes = Base.classes.Genes 

Address = Base.classes.address 
#Start Session 
session = Session(engine) 
#add a row: 
session.add(Genes(Gene_Id=1,Gene_Symbol = "GENE_SYMBOL", Gene_Description="GENE_DESCRIPTION")) 
session.commit() 
q = session.query(Genes).all() 
for gene in q: 
    print "This is the Gene ID {},\n This is the Gene Desc {},\n this is the Gene symbol {}.".format(gene.Gene_Id,gene.Gene_Description, gene.Gene_Symbol) 
+0

我剛剛也得到了'NoneType'錯誤,我想說它可能值得將其添加到問題本身:) –

+0

就像一個引用,你必須有一個主鍵來做自動映射。否則它不會自動映射: https://stackoverflow.com/questions/23765681/sqlalchemy-automap-does-not-create-class-for-tables-without-primary-key – Kevin