1import java.sql.*;
2
3/**
4 * A Java MySQL SELECT statement example.
5 * Demonstrates the use of a SQL SELECT statement against a
6 * MySQL database, called from a Java program.
7 *
8 * Created by Alvin Alexander, http://alvinalexander.com
9 */
10public class JavaMysqlSelectExample
11{
12
13 public static void main(String[] args)
14 {
15 try
16 {
17 // create our mysql database connection
18 String myDriver = "org.gjt.mm.mysql.Driver";
19 String myUrl = "jdbc:mysql://localhost/test";
20 Class.forName(myDriver);
21 Connection conn = DriverManager.getConnection(myUrl, "root", "");
22
23 // our SQL SELECT query.
24 // if you only need a few columns, specify them by name instead of using "*"
25 String query = "SELECT * FROM users";
26
27 // create the java statement
28 Statement st = conn.createStatement();
29
30 // execute the query, and get a java resultset
31 ResultSet rs = st.executeQuery(query);
32
33 // iterate through the java resultset
34 while (rs.next())
35 {
36 int id = rs.getInt("id");
37 String firstName = rs.getString("first_name");
38 String lastName = rs.getString("last_name");
39 Date dateCreated = rs.getDate("date_created");
40 boolean isAdmin = rs.getBoolean("is_admin");
41 int numPoints = rs.getInt("num_points");
42
43 // print the results
44 System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);
45 }
46 st.close();
47 }
48 catch (Exception e)
49 {
50 System.err.println("Got an exception! ");
51 System.err.println(e.getMessage());
52 }
53 }
54}
55
12, Fred, Flinstone, 2010-06-23, false, 6000
23, Barney, Rubble, 2010-06-23, false, 5000
3