Advertisement
Guest User

Select

a guest
Jun 27th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import 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. */
  10. public class JavaMySQLSelect
  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.  
  40. // print the results
  41. System.out.format("%s, %s, %s ,\n", id, firstName, lastName);
  42. }
  43. st.close();
  44. }
  45. catch (Exception e)
  46. {
  47. System.err.println("Got an exception! ");
  48. System.err.println(e.getMessage());
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement