Advertisement
Guest User

Untitled

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