>>>c.executemany('insert into portfolio values (?,?,?)',stocks)
<sqlite3.Cursorobjectat0x10067a730>
>>>db.commit()
>>>
To perform a query, use a statement such as this:
为了执行某个查询,使用像下面这样的语句:
..code-block::python
>>>forrowindb.execute('select * from portfolio'):
...print(row)
...
('GOOG',100,490.1)
('AAPL',50,545.75)
('FB',150,7.45)
('HPQ',75,33.2)
>>>
如果你想接受用户输入作为参数来执行查询操作,必须确保你使用下面这样的占位符?来进行参数转义:
..code-block::python
>>>min_price=100
>>>forrowindb.execute('select * from portfolio where price >= ?',
(min_price,)):
...print(row)
...
('GOOG',100,490.1)
('AAPL',50,545.75)
>>>
----------
讨论
----------
todo...
At a low level, interacting with a database is an extremely straightforward thing to do.
You simply form SQL statements and feed them to the underlying module to either
update the database or retrieve data. That said, there are still some tricky details you’ll
need to sort out on a case-by-case basis.
One complication is the mapping of data from the database into Python types. For
entries such as dates, it is most common to use datetime instances from the date
time module, or possibly system timestamps, as used in the time module. For numerical
data, especially financial data involving decimals, numbers may be represented as Dec
imal instances from the decimal module. Unfortunately, the exact mapping varies by
database backend so you’ll have to read the associated documentation.
Another extremely critical complication concerns the formation of SQL statement
strings. You should never use Python string formatting operators (e.g., %) or the .for
mat() method to create such strings. If the values provided to such formatting operators
are derived from user input, this opens up your program to an SQL-injection attack (see
http://xkcd.com/327). The special ? wildcard in queries instructs the database backend
to use its own string substitution mechanism, which (hopefully) will do it safely.
Sadly, there is some inconsistency across database backends with respect to the wildcard.
Many modules use ? or %s, while others may use a different symbol, such as :0 or :1,
to refer to parameters. Again, you’ll have to consult the documentation for the database
module you’re using. The paramstyle attribute of a database module also contains information
about the quoting style.
For simply pulling data in and out of a database table, using the database API is usually
simple enough. If you’re doing something more complicated, it may make sense to use
a higher-level interface, such as that provided by an object-relational mapper. Libraries
such as SQLAlchemy allow database tables to be described as Python classes and for
database operations to be carried out while hiding most of the underlying SQL.
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.