thieumao

Select - MySQL - Java

Oct 31st, 2013
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. package testmysql;
  2.  
  3. import java.sql.*;
  4.  
  5. public class JavaMysqlSelectExample {
  6.  
  7.     public static void main(String[] args) {
  8.         try {
  9.             // create our mysql database connection
  10.             String myDriver = "org.gjt.mm.mysql.Driver";
  11.             String myUrl = "jdbc:mysql://localhost/TestMySQL";
  12.             Class.forName(myDriver);
  13.             Connection conn = DriverManager.getConnection(myUrl, "root", "admin");
  14.  
  15.             // our SQL SELECT query.
  16.             // if you only need a few columns, specify them by name instead of using "*"
  17.             String query = "SELECT * FROM user";
  18.  
  19.             // create the java statement
  20.             Statement st = conn.createStatement();
  21.  
  22.             // execute the query, and get a java resultset
  23.             ResultSet rs = st.executeQuery(query);
  24.  
  25.             // iterate through the java resultset
  26.             while (rs.next()) {
  27.                 int id = rs.getInt("id");
  28.                 String username = rs.getString("username");
  29.                 String password = rs.getString("password");
  30.                 int level = rs.getInt("level");
  31.  
  32.                 // print the results
  33.                 System.out.format("%s, %s, %s, %s\n", id, username, password, level);
  34.             }
  35.             st.close();
  36.         } catch (Exception e) {
  37.             System.err.println("Got an exception! ");
  38.             System.err.println(e.getMessage());
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment