How to use Sqlalchemy core with text sql for date range?

sqlalchemy select columns
sqlalchemy text
sqlalchemy core vs orm
sqlalchemy raw sql
sqlalchemy execute
sqlalchemy not null
flask-sqlalchemy
sqlalchemy introduction
s = text('SELECT customers.id,WHERE customers.end_date IS NULL or customers.end_date >= '+ "2018-05-01"+ 'AND customers.end_date <='+"2018-05-31" + 'ORDER BY customers.id;')

This throws syntax errors. How exactly do I pass the date values in the above statement? How to foramte the date string? Using sqlalchemy core version 1.0.8 only, python 2.7

try this:

    s = text('SELECT customers.id WHERE customers.end_date IS NULL or 
   customers.end_date >= \'2018-05-01\' AND customers.end_date 
    <= \'2018-05-31\' ORDER BY customers.id;')

SQL Expression Language Tutorial, from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey Methods here range from using cursor.lastrowid , to selecting from a textual SQL to existing Core or ORM models, because we can use column as result-​set behaviors, such as date and numeric coercions, the type may  With the basics in place, we can now try executing some raw SQL using SQLAlchemy. Using the Text Module. One method for executing raw SQL is to use the text module, or Textual SQL. The most readable way to use text is to import the module, then after connecting to the engine, define the text SQL statement string before using .execute to run it:

There are multiple potential syntax errors. The first is the extra comma at the end of the SELECT item list, before the WHERE clause. The second (and third) the missing quotes around the literal that you're comparing against. The missing spaces also alter how the query is parsed. After string concatenation the result looks like:

In [2]: s
Out[2]: 'SELECT customers.id,WHERE customers.end_date IS NULL or customers.end_date >= 2018-05-01AND customers.end_date <=2018-05-31ORDER BY customers.id;'

which is clearly wrong.

As always, don't pass values to SQL queries with string concatenation or formatting, unless they're static, in which case they're a part of your query to begin with. If you do, you might expose yourself to SQL injection. The driver you're using knows how to handle different data types, quoting etc. better than you – probably. Use placeholders:

s = text('''SELECT customers.id
            WHERE customers.end_date IS NULL
               OR customers.end_date >= :end_date_low
              AND customers.end_date <= :end_date_high
            ORDER BY customers.id''')
low = "2018-05-01"
high = "2018-05-31"

# engine, connection, or session
conn.execute(s, end_date_low=low, end_date_high=high)

In addition you could use the SQL operator BETWEEN here:

s = text('''SELECT customers.id
            WHERE customers.end_date IS NULL
               OR customers.end_date BETWEEN :end_date_low AND :end_date_high
            ORDER BY customers.id''')

Column and Data Types, SQLAlchemy will use the Integer and String(32) type information when Date and time types return objects from the Python datetime module. otherwise numeric coercion between float / Decimal may or may not function as expected. in generic SQLAlchemy Core, we can't assume the return type at SQL  That’s why SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged.

Be careful when concatenating strings, you might miss some spaces. For example: "2018-05-01"+ 'AND customers.end_date <=' => "2018-05-01AND customers.end_date <='. Etc.

The other thing is adding quotes around date inside query. In your case quotes around are not part of query. So you could write instead: "'2018-05-01'"+ ' AND customers.end_date <='.

Or see the full example by @Dataichou

SQLAlchemy Core, In contrast to the ORM's domain-centric mode of usage, the SQL Expression Language provides a schema-centric usage paradigm. Before we get into the SQLAlchemy aspects, let’s take a second to look at how to connect to a SQL database with the mysql-python connector (or at least take a look at how I do it). First, let’s setup our import statements. For this, we will import MySQLdb, pandas and pandas.io.sql in order to read SQL data directly into a pandas dataframe.

Column Elements and Expressions, The between() function is a standalone version of the SQLAlchemy's Core expression system makes wide use of bindparam() in an implicit sense. For example, a bindparam() which refers to a datetime value, and is specified as and the string SQL statement will be transformed on a per-execution  Btw, instead of '1985-01-17', you can also use datetime.date(1985, 1, 17) - may be easier to get at or work with in some environments. – rippleslash Dec 22 '15 at 22:27 5 @rippleslash: you are right, and ideally one should use the proper data type for parameters.

SQL Expressions, Current Release Series (1.3) · Maintenance Release (1.2) · Development Access Release: 1.3.16 current release | Release Date: April 7, 2020 The “​stringification” of a SQLAlchemy Core statement object or expression Never use this technique with string content received from untrusted input, such as from web forms  attribute sqlalchemy.types.Date. python_type¶. Return the Python type object expected to be returned by instances of this type, if known. Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

Working with Engines and Connections, This section details direct usage of the Engine , Connection , and related objects. Our example above illustrated the execution of a textual SQL string. modes, the core behavior of DBAPI per PEP-0249 is that a transaction is always in used to associate a series of Table objects and all SQL constructs derived from them  The type dictates what kind of data a column can take. SQLAlchemy provides an abstraction for a wide range of types. Broadly speaking there are three categories of types. Generic Types; SQL Standard Types; Vendor Specific Types; Generic Types. The Generic types refer to the common types which major database backends support.

Comments
  • that was real quick and perfect !
  • Thanks. Also remember to follow the advices given on the answers given by Ilja and Andrew