Download stmt.executeUpdate(insertString)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Database model wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Transcript
Exceptions
An exception is an object that describes
an unusual or erroneous situation
Exceptions are thrown by a program,
and may be caught and handled by
another part of the program
Exception Hierarchy
Errors:


Errors are caused by bugs in the Java VM, or by the
program running out of memory or other resources.
Errors are usually not handled by programs.
Exceptions:





Exceptions can be caused by bugs in the program or
improper data supplied to the program
Exceptions should be handled, or caught
An exception is either checked or unchecked
Checked exceptions must be caught or declared as thrown.
You are not required to handle unchecked exceptions.
Exception Handling
Try-catch block and finally block
try {
// code may cause/throw exceptions
} catch (Exception1 e1) {
// handle Exception1
} catch (Exception2 e2) {
// handle Exception2
} finally {
// optional
// code always executed whether an exception
//
is thrown or not
}
Define Your Own Exception
public class MyException extends Exception
{
public MyException(String msg)
{
super(msg);
}
}
Throw Statement and
Throws Clause
public class MyClass
{
public void aMethod(int i, int j)
throws MyException
{
// ...
throw new MyException(reason);
// ...
}
}
I/O Streams
A stream is a sequence of bytes.
In a program, we read information from
an input stream and write information
to an output stream
An I/O stream is either a


character stream, which deals with text
data
byte stream, which deal with binary data
Two Types of I/O
Stream-based I/O supports reading or writing
data sequentially.
A stream may be opened for either reading or writing, but not
both.
Random access I/O supports reading and
writing data at any position of a file.
A random access file may be opened for both reading and
writing.
Standard I/O Streams
There are three standard I/O streams:
standard input – System.in
standard output – System.out
standard error – System.err
Some classes used for I/O
FileInputStream
Reads bytes from a file
Reader
Abstract class for reading character
streams
InputStreamReader
Reads bytes & translates into
characters
BufferedReader
Read character-input and builds lines or
arrays
StreamTokenizer
Parse strings into tokens
OutputStream
Abstract class to outputting bytes
FileOutputStream
Write data to a file
Writer
Write character streams
Common Text Input Combinations
Read character at a time from a FileInputStream(fileName)
text file
InputStreamReader
Read one line at a time from a
text file
FileInputStream (fileName)
InputStreamReader
BufferedReader
Read one word at a time from a FileInputStream (fileName)
text file
InputStreamReader
BufferedReader
StreamTokenizer
Read Keyboard input
InputStreamReader(System.in)
BufferedReader
Read int, double, etc. from a
non-text file
FileInputStream(fileName)
DataInputStream
I/O Program Examples
ReadCharacters.java
ReadLines.java
ReadWords.java
Reading/Writing Text Files
The reader and writer classes can handle text
I/O. Handle conversion between Unicode and
native character encoding
May throw IOException
BufferedReader in
= new BufferedReader(
new FileReader("foo.in"));
PrintWriter out
= new PrintWriter(
new BufferedWriter(
new FileWriter("foo.out")));
Example: InventoryItem.java
import java.text.DecimalFormat;
public class InventoryItem {
private String name;
private int units;
private float price;
private DecimalFormat fmt;
public InventoryItem(String itemName, int numUnits,
float cost) {
name = itemName;
units = numUnits;
price = cost;
fmt = new DecimalFormat ("0.##");
}
public String toString() {
return name + ":\t" + units + " at " + price +
" = " + fmt.format ((units * price));
}
}
Example: Inventory.java
import java.util.StringTokenizer;
import java.io.*;
public class Inventory {
public static void main (String[] args) {
final int MAX = 100;
InventoryItem[] items = new InventoryItem[MAX];
StringTokenizer tokenizer;
String line, name, file="inventory.dat";
int units, count = 0;
float price;
try {
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
Example: Inventory.java
while (line != null) {
tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
try {
units = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
items[count++] =
new InventoryItem(name, units, price);
} catch (NumberFormatException exception) {
System.out.println("Error in input. Line ignored:")
System.out.println(line);
}
line = inFile.readLine();
}
inFile.close();
Example: Inventory.java
for (int scan = 0; scan < count; scan++)
System.out.println(items[scan]);
} catch (FileNotFoundException exception) {
System.out.println("The file " + file +
" was not found.");
} catch (IOException exception) {
System.out.println(exception);
}
}
}
Example: Inventory
Input
Widget 14 3.35
Spoke 132 0.32
Wrap 58 1.92
Thing 28 4.17
Brace 25 1.75
Clip 409 0.12
Cog 142 2.08
Output
Widget:
Spoke:
Wrap:
Thing:
Brace:
Clip:
Cog:
14 at 3.35 = 46.9
132 at 0.32 = 42.24
58 at 1.92 = 111.36
28 at 4.17 = 116.76
25 at 1.75 = 43.75
409 at 0.12 = 49.08
142 at 2.08 = 295.36
Example: TestData.java
final int MAX = 10;
int value;
String file = "test.dat";
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int line=1; line <= MAX; line++) {
for (int num=1; num <= MAX; num++) {
value = (int) (Math.random() * 100);
outFile.print(value + "
");
}
outFile.println();
}
outFile.close();
Example: TestData Output
12
20
43
32
90
45
0
54
47
95
92
12
4
41
25
57
86
93
12
90
80
34
13
35
54
50
19
54
79
77
25
69
83
20
59
6
70
31
2
76
40
27
68
7
30
95
75
43
82
63
10
4
63
50
88
90
21
54
33
16
25
43
12
89
61
66
98
74
22
12
82
50
50
67
92
17
30
35
81
30
89
17
39
64
36
20
68
49
28
1
6
27
80
19
10
92
44
26
89
60
JDBC
Java Database Connectivity
Steps:
1.
2.
3.
4.
Load a JDBC driver
Establish a connection with a data base
Send queries and update statements
Process the results
Setting up an Access Database
Driver for Windows
Open the “ODBC Data Sources (32 bit)” folder
Start|Settings|Control Panel|ODBC Data Sources (32 bit)
Select the System DSN tab (top of the dialog box)
Click on the Add… button (at the right)
Select Microsoft Access Driver(*.mdb) from the list box
Click “Finish”
A dialog box with the title ODBC Microsoft Access Setup will appear,


Type a description in the Description Text field (optional)
In the Database section,
 click on the Select button,
 find and select your saved version of the access.mdb database,
 Click OK
Click OK in the ODBC Microsoft Access Setup Dialog
The System DSN section of the initial ODBC Data Source Administrator
dialog should now have the new mdb database name in the list of
system data sources.
The UserPass Table
username
password
Bill Gates
blue
Scott McNealy
lavender
Steve Jobs
aqua
Example: BuildUserDB_Access.java
import java.sql.*;
import java.io.*;
import java.util.*;
public class BuildUserDB_Access {
public static final String database =
"Access 2000";
public static final String jdbcDriver =
"sun.jdbc.odbc.JdbcOdbcDriver";
public static final String dataSource =
"jdbc:odbc:";
public static void main(String args[]) {
String dbName = "Users";
String tableName = "UserPass";
Connection conn = null;
Statement stmt = null;
Example: BuildUserDB_Access.java
try {
Class.forName(jdbcDriver);
} catch(ClassNotFoundException e) {
System.exit(1);
}
try {
String url = dataSource + dbName;
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
} catch (SQLException se) {
System.exit(1);
}
Example: BuildUserDB_Access.java
try {
String dropString = "DROP TABLE " + tableName;
stmt.executeUpdate(dropString);
} catch (SQLException se) {}
try {
String createString =
"CREATE TABLE " + tableName +
" (username VARCHAR(128) NOT NULL PRIMARY KEY," +
" password VARCHAR(128))";
stmt.executeUpdate(createString);
Example: BuildUserDB_Access.java
String insertString =
"INSERT INTO " + tableName +
" VALUES ('Scott McNealy', 'lavender')";
stmt.executeUpdate(insertString);
insertString =
"INSERT INTO " + tableName +
" VALUES ('Steve Jobs', 'aqua')";
stmt.executeUpdate(insertString);
insertString =
"INSERT INTO " + tableName +
" VALUES ('Bill Gates', 'blue')";
stmt.executeUpdate(insertString);
Example: BuildUserDB_Access.java
ResultSet rset =
stmt.executeQuery("SELECT * FROM " + tableName);
while( rset.next() ) {
System.out.println(rset.getString("username") +
":" +
rset.getString("password"));
}
stmt.close();
rset.close();
conn.close();
} catch (SQLException se) {}
}
}
Thread
A sequential flow of control within a
program
All programs have at least one thread
In Java, the thread is


Application: main()
Applet:
Browser is main thread
Java is a multi-threaded language
Creating Threads in Java
Create an object of Thread by


Subclass Thread
Provide definition of run() method
Implement Runnable interface


Declare run() method
Create Thread object when needed
Subclassing the Thread Class
public class SimpleThread extends Thread {
…..
public void run() {
// provide an override for run() method
}
}
Implement Runnable Inteface
public class Test extends Applet implements Runnable{
private Thread testThread = null;
…
// when needed, create instance of Thread
testThread = new Thread(this, “Test”);
Two types of thread
Daemon thread
• background thread subordinate to creator thread
• ends when creator thread ends
• threads that run indefinitely usually are created as
daemon threads
User thread
• independent of creator thread
• has life of its own!
• run() method returns after done or it must be explicitly
stopped or destroyed
Threads and priority scheduling
Can run in parallel if there are multiple processors.
On a single CPU, threads are scheduled
Threads are scheduled based on priority relative to
other threads
system chooses the runnable thread with highest
priority; which runs until
it yields (to thread with same priority) or exits
run() or is preempted
Thread Priority
Threads inherit priority from their creator



can be modified afterwards
MIN_PRIORITY (1) to MAX_PRIORITY (10)
NORM_PRIORITY (5) is default
Time Slicing and Priority Scheduling
Time-slicing


implemented by some OSs to fight selfish thread behavior
each process gets a quantum of time, executes in a “round-robin”
fashion; i.e., each in turn
Priority Scheduling




threads at same priority can share as above
threads at lower priority must wait
threads at higher priority preempt lower threads
but lower priority thread may be run to avoid starvation
– up to the thread scheduler in JVM
Stopping Threads
Stop when the task is finished (a ‘natural’ death)
thread arranges for own termination; run() method
terminates ‘naturally’
interrupt()


one thread signals another thread that it should stop
just sets a flag; does not stop the thread
isInterrupted()

checks to see if a thread has been interrupted (may still be running)
isAlive()


checks to see if a thread is still operating
if true, thread is started and not stopped; may be Runnable or Not
Runnable
Thread Synchronization
At times it is necessary to limit resources to one
user at a time.


use an internal lock to ensure only one thread
among competitors gains access to critical sections of
code
A thread acquires the lock by executing:
 a synchronized instance method of that object.
 body of a synchronized statement that synchronizes on the
object.
 a synchronized static method of a class.
Synchronization at the Method level
synchronized public void method1() {...
// at the code block level
synchronized(theObject) statement
Waiting for a Thread
join()

waits until thread dies; no synchronization used
thread1.join(); // waits until thread1 dies
thread1.join(1000); // wait up to 1 second
sleep(long millisec)

suspend execution for specified time
can throw InterruptedException,

so must be in try block or must indicate calling
method throws this exception