码迷,mamicode.com
首页 > 数据库 > 详细

Using databases and Structured Query Language (SQL)

时间:2015-12-19 16:36:06      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:

//The code to create a database file and a table named Tracks with two columns in the database is as follows:

1 #!/usr/bin/python
2 import sqlite3
3 conn = sqlite3.connect(music.sqlite3)
4 cur  = conn.cursor()
5 cur.execute(DROP TABLE IF EXISTS Tracks )
6 cur.execute(CREATE TABLE Tracks (title TEXT,plays INTEGER))
7 conn.close()

The connect operation makes a “connection” to the database stored in the file music.sqlite3 in the current directory. If the file does not exist, it will be created. The reason this is called a “connection” is that sometimes the database is  stored on a separate “database server” from the server on which we are running our application. In our simple examples the database will just be a local file in the same directory as the Python code we are running.
A cursor is like a file handle that we can use to perform operations on the data stored in the database. Calling cursor() is very similar conceptually to calling open() when dealing with text files.

技术分享

Once we have the cursor, we can begin to execute commands on the contents of the database using the execute() method.
The database language is called Structured Query Language or SQL  for short.
http://en.wikipedia.org/wiki/SQL
In our example, we are executing two SQL commands in our database. As a convention, we will show the SQL keywords in uppercase and the parts of the command that we are adding (such as the table and column names) will be shown in lowercase.
The first SQL command removes the Tracks table from the database if it exists. This pattern is simply to allow us to run the same program to create the Tracks table over and over again without causing an error. Note that the DROP TABLE command deletes the table and all of its contents from the database (i.e., there is no “undo”).
cur.execute(‘DROP TABLE IF EXISTS Tracks ‘)
The second command creates a table named Tracks with a text column named title and an integer column named plays.
cur.execute(‘CREATE TABLE Tracks (title TEXT, plays INTEGER)‘)
Now that we have created a table named Tracks, we can put some data into that table using the SQL INSERT operation. Again, we begin by making a connection to the database and obtaining the cursor. We can then execute SQL commands using the cursor.
The SQL INSERT command indicates which table we are using and then defines a new row by listing the fields we want to include (title, plays) followed by the VALUES we want placed in the new row. We specify the values as question marks (?, ?) to indicate that the actual values are passed in as a tuple ( ’My Way’,15 ) as the second parameter to the execute() call.

 1 #!/usr/bin/python
 2 import sqlite3
 3 conn = sqlite3.connect(music.sqlite3)
 4 cur  = conn.cursor()
 5 cur.execute(INSERT INTO Tracks (title,plays) VALUES (?,?),
 6             (Thunderstruck,20))
 7 cur.execute(INSERT INTO Tracks (title,plays) VALUES (?,?),
 8             (My Way,15))
 9 conn.commit()
10 print  Tracks:
11 cur.execute(SELECT title, plays FROM Tracks)
12 for row in cur:
13     print row
14 cur.execute(DELETE FROM Tracks WHERE plays < 100)
15 conn.commit()
16 cur.close()

OUTPUT:

Tracks:
(uThunderstruck, 20)
(uMy Way, 15)

First we INSERT two rows into our table and use commit() to force the data to be written to the database file.
技术分享

Then we use the SELECT command to retrieve the rows we just inserted from the table. On the SELECT command, we indicate which columns we would like (title, plays) and indicate which table we want to retrieve the data from. After we execute the SELECT statement, the cursor is something we can loop through in a for statement. For efficiency, the cursor does not read all of the data from the database when we execute the SELECT statement. Instead, the data is read on demand as we loop through the rows in the for statement.
Our for loop finds two rows, and each row is a Python tuple with the first value as the title and the second value as the number of plays. Do not be concerned that the title strings are shown starting with u’. This is an indication that the strings are Unicode strings that are capable of storing non-Latin character sets.
At the very end of the program, we execute an SQL command to DELETE the rows we have just created so we can run the program over and over. The DELETE command shows the use of a WHERE clause that allows us to express a selection criterion so that we can ask the database to apply the command to only the rows that match the criterion. In this example the criterion happens to apply to all the rows so we empty the table out so we can run the program repeatedly. After theDELETE is performed, we also call commit() to force the data to be removed from the database.

Structured Query Language summary
So far, we have been using the Structured Query Language in our Python examples and have covered many of the basics of the SQL commands. In this section, we look at the SQL language in particular and give an overview of SQL syntax.Since there are so many different database vendors, the Structured Query Language (SQL) was standardized so we could communicate in a portable manner to database systems from multiple vendors.
A relational database is made up of tables, rows, and columns. The columns generally have a type such as text, numeric, or date data. When we create a table, we indicate the names and types of the columns:
CREATE TABLE Tracks (title TEXT, plays INTEGER)
To insert a row into a table, we use the SQL INSERT command:
INSERT INTO Tracks (title, plays) VALUES (‘My Way‘, 15)
The INSERT statement specifies the table name, then a list of the fields/columns that you would like to set in the new row, and then the keyword VALUES and a list of corresponding values for each of the fields.
The SQL SELECT command is used to retrieve rows and columns from a database.The SELECT statement lets you specify which columns you would like to retrieve as well as a WHERE clause to select which rows you would like to see. It also allows an optional ORDER BY clause to control the sorting of the returned rows.
SELECT * FROM Tracks WHERE title = ‘My Way‘
Using * indicates that you want the database to return all of the columns for each row that matches the WHERE clause.
Note, unlike in Python, in a SQL WHERE clause we use a single equal sign to indicate a test for equality rather than a double equal sign. Other logical operations allowed in a WHERE clause include <, >, <=, >=, !=, as well as AND and OR and parentheses to build your logical expressions.
You can request that the returned rows be sorted by one of the fields as follows:
SELECT title,plays FROM Tracks ORDER BY title
To remove a row, you need a WHERE clause on an SQL DELETE statement. The WHERE clause determines which rows are to be deleted:
DELETE FROM Tracks WHERE title = ‘My Way‘
It is possible to UPDATE a column or columns within one or more rows in a table using the SQL UPDATE statement as follows:
UPDATE Tracks SET plays = 16 WHERE title = ‘My Way‘
The UPDATE statement specifies a table and then a list of fields and values to change after the SET keyword and then an optional WHERE clause to select the rows that are to be updated. A single UPDATE statement will change all of the rows that match
the WHERE clause. If a WHERE clause is not specified, it performs the UPDATE on all of the rows in the table.
These four basic SQL commands (INSERT, SELECT, UPDATE, and DELETE)
allow the four basic operations needed to create and maintain data.



Using databases and Structured Query Language (SQL)

标签:

原文地址:http://www.cnblogs.com/peng-vfx/p/5059296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!