Advertisement
Guest User

Untitled

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