Monday, 6 March 2017

Chapter 32 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

32.8 (Populate Salary table) Create a table named Salary as follows:
create table Salary(
firstName varchar(100),
lastName varchar(100),
rank varchar(15),
salary float);
Obtain the data for salary from http://cs.armstrong.edu/liang/data/Salary.txt and populate it into the Salary table in the database.


import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Exercise08 {

 public static void main(String[] args) throws MalformedURLException, IOException, ClassNotFoundException, SQLException {
  Scanner input = new Scanner(new BufferedInputStream(new URL("http://cs.armstrong.edu/liang/data/Salary.txt").openStream()));
  
  Class.forName("com.mysql.jdbc.Driver");
  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "root", "root");
  String queryString = "insert into Salary (firstName, lastName, rank, salary) values (?, ?, ?, ?);";
  
  while(input.hasNextLine()) {
   PreparedStatement preparedStatement = connection.prepareStatement(queryString);
   preparedStatement.setString(1, input.next());
   preparedStatement.setString(2, input.next());
   preparedStatement.setString(3, input.next());
   preparedStatement.setString(4, input.next());
   preparedStatement.executeUpdate();
  }
  input.close();
 }

}

No comments :

Post a Comment