Advertisement
Guest User

Untitled

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