Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab2;
- import java.sql.*;
- import java.util.Scanner;
- public class JavaMysqlSelectExample {
- public static void main(String[] args) {
- try
- {
- // create the mysql database connection
- String myDriver = "com.mysql.jdbc.Driver";
- //specify the database to connect
- String myUrl = "jdbc:mysql://localhost/studentcontact";
- //connect to the database
- Class.forName(myDriver);
- Connection conn = DriverManager.getConnection(myUrl, "root", "");
- // create the SQL select statement.
- String query = "SELECT avg(height) as avg FROM student";
- // create the java statement
- Statement st = conn.createStatement();
- // execute the query; the result of the execution is stored in an object of ResultSet class
- ResultSet rs = st.executeQuery(query);
- // there can be more than one result. so, we have to go through each data. in each round, only one record will be readed.
- while (rs.next())
- {
- System.out.println(rs.getString("avg"));
- }
- st.close();
- }
- catch (Exception e)
- {
- System.err.println("Got an exception! ");
- System.err.println(e.getMessage());
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement