Another Java example
This one uses command line arguments, it creates a file using java.io and it connects to a database using java.sql.
//We want to use a file (input/output) and a SQL database. import java.io.*; import java.sql.*; public class Test { //Try to call this program from the command line, e.g.: //java Test 1.7 2.3 3.8 //Or use Eclipse and select "Run...", you can type //arguments there. public static void main(String[] args) { double sum = 0; for (int i = 0; i < args.length; i++) { //System.out.println(args[i]); try { sum += Double.parseDouble(args[i]); //This does the same as above: //sum += Double.valueOf(args[i]).doubleValue(); } catch (Exception e) { //Print message if an argument isn't a number. System.out.println("Not a number: " + args[i]); } } double avg = sum / args.length; System.out.println("No of args: " + args.length); System.out.println("Sum: " + sum + ", Avg: " + avg); File file = new File("sum.txt"); try { //Create a file and store the average value on disk. FileOutputStream stream = new FileOutputStream(file); stream.write(String.valueOf(avg).getBytes()); } catch (Exception e) { //This happens if the file is write protected //(you can try this) or any other error occurs. System.out.println("Oops!"); } try { //Load the driver and connect to the database. //This example uses Access, but a "real" //database like MySQL is a lot better. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //For ODBC you have to create an "ODBC Data //Source" in the Windows Control Panel. Connection con = DriverManager.getConnection( "jdbc:odbc:NameOfTheODBCDataSource"); //Create an empty statement. Statement stmt = con.createStatement(); //Use the statement to insert the average value two times. //You have to replace the table and column names! stmt.execute("INSERT INTO tablename " + "(columnname) VALUES ('" + avg + "')"); stmt.execute("INSERT INTO tablename " + "(columnname) VALUES ('" + avg + "')"); //Use the same statement to select something. ResultSet res = stmt.executeQuery("SELECT * FROM tablename"); //Walk through the result set. while (res.next()) { System.out.println(res.getString("columnname")); } } catch (Exception e) { //This happens when the database or table does not exist //or any other error according to SQL occurs. e.printStackTrace(); } } }
Kommentare
Noch keine Beiträge.
Einen Kommentar abgeben
Sorry, das Kommentarformular ist derzeit abgeschaltet.