Advertisement
Guest User

Untitled

a guest
Aug 25th, 2016
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import java.sql.*;
  2. public class JavaMysqlSelectExample {
  3. public static void main(String[] args) {
  4. try
  5. {
  6. // create the mysql database connection
  7. String myDriver = "com.mysql.jdbc.Driver";
  8.  
  9. //specify the database to connect
  10. String myUrl = "jdbc:mysql://localhost/studentcontact";
  11.  
  12. //connect to the database
  13. Class.forName(myDriver);
  14. Connection conn = DriverManager.getConnection(myUrl, "root", "");
  15.  
  16. // create the SQL select statement.
  17. String query = "SELECT * FROM student";
  18.  
  19. // create the java statement
  20. Statement st = conn.createStatement();
  21.  
  22. // execute the query; the result of the execution is stored in an object of ResultSet class
  23. ResultSet rs = st.executeQuery(query);
  24.  
  25. // there can be more than one result. so, we have to go through each data. in each round, only one record will be readed.
  26. while (rs.next())
  27. {
  28. int id = rs.getInt("Id");
  29. String firstName = rs.getString("firstname");
  30. String lastName = rs.getString("lastname");
  31. int age = rs.getInt("age");
  32. float height = rs.getInt("height");
  33.  
  34.  
  35. // print the results
  36. //System.out.format("%s, %s, %s, %s, %s\n", id, firstName, lastName, age, height);
  37.  
  38. //System.out.format("%s\n", id);
  39. //System.out.format("%s\n", firstName);
  40. //System.out.format("%s, %s, %s, %s\n", firstName, lastName, age, height);
  41.  
  42. }
  43. st.close();
  44. }
  45. catch (Exception e)
  46. {
  47. System.err.println("Got an exception! ");
  48. System.err.println(e.getMessage());
  49. e.printStackTrace();
  50. }
  51.  
  52. }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement