The SQL SELECT Statement
A relational database consists of rectangular
tables with rows and columns. A SELECT statement can
be used by a Java application to to extract some of the
information in a table and place it in a ResultSet object.
This object can be used to display or further process the
data. Here are some examples of SQL statements extracting
information from the Kids database, which contains the single
table Roster.
- SELECT * FROM Roster
Select all rows and columns from the table Roster.
- SELECT Name FROM Roster
Select all rows, but only the column Name.
- SELECT Name, Age FROM Roster
Select all rows and the columns Name and Age.
- SELECT * FROM Roster WHERE Name = 'Chloe'
Select all columns, but only the row with the name Chloe.
- SELECT Name FROM Roster WHERE ID = 8630
Select the name with the ID 8630.
- SELECT * FROM Roster WHERE Gender = 'F' and
Age = 9
Select all columns and only the rows with Gender F and Age 9.
Sometimes, an SQL must be constructed from information supplied at
runtime. Suppose that you want to select all columns from the table
where the name is supplied in the textfield called kidName. Here is
what you do:
SQL = "SELECT * FROM Roster WHERE Name = '" +
kidName.getText() + "'"
Note that text constants in SQL must be enclosed in single quotes,
even when the text constant is obtained from a variable at run time.