daily pastebin goal
15%
SHARE
TWEET

Untitled

a guest Sep 22nd, 2016 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.          
  30.           // there can be more than one result. so, we have to go through each data. in each round, only one record will be readed.
  31.          
  32.               while (rs.next())
  33.               {
  34.                   System.out.println(rs.getString("avg"));
  35.               }
  36.          
  37.           st.close();
  38.         }
  39.         catch (Exception e)
  40.         {
  41.           System.err.println("Got an exception! ");
  42.           System.err.println(e.getMessage());
  43.           e.printStackTrace();
  44.         }
  45.  
  46.     }
  47.  
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top