Please install JDK 1.3.1_02 or later with Java Plugin to view this page. Also, this page is best viewed with browsers (for examples, Mozilla 0.99 or later, IE 6.x or later) with CSS2 support. This document is provided as is. You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu
dbUser=monkey dbPasswd=password
import java.util.*;
import java.io.*;
public class LoadProperty
{
public static void main(String argv[])
{
Properties props = new Properties();
try {
props.load(new FileInputStream("meta.txt"));
} catch (IOException ioe) {
System.out.println("Open meta.txt Error!");
System.exit(1);
}
System.out.println(props.getProperty("dbUser"));
System.out.println(props.getProperty("dbPasswd"));
}
}
//
// to run this program, please enter the following command
// java -DSchool=<some value> TestSystem
//
public class TestSystem {
public static void main(String[] args) {
// print out the default system properties
System.out.println("CLASSPATH = " +
System.getProperty("java.class.path"));
System.out.println("OS Version = " + System.getProperty("os.version"));
// check to see if user enter property "School"
// if none is found, the default value "x" is set
if (System.getProperty("School", "x").equals("x"))
System.out.println("Usage: java -DSchool=<some value> TestSystem");
else
System.out.println("You are a student of " +
System.getProperty("School"));
}
}
「開始」 --> 「設定」 --> 「控制台」 --> 「ODBC」 --> 「系統資料來源名稱」 --> 「新增」 --> 「Microsoft Access Driver (*.mdb)」 --> 「完成」
幾個簡單的 SQL 範例:
insert into Product values ('5','燒錄器', 15000, 10)
select * from Product
select * from Product where Name='燒錄器'
select Name, Qty from Product where Name='燒錄器'
select * from Product where Price < 2500
select * from Product where Price >= 300 and Price < 10000
update Product set Qty=20 where Name='燒錄器'
delete from Product where Name='燒錄器'
Statement aStatement = conn.createStatement(); ResultSet rs = aStatement.executeQuery(aQuery);
import java.sql.*;
public class OldJavaDB
{
public static void main( String argv[] )
{
// initialize query string
String aQuery = "select * from Product";
try
{
// load the JDBC-ODBC bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// connect to Database
Connection conn = DriverManager.getConnection("jdbc:odbc:Samples");
// Construct a SQL statement and submit it
Statement aStatement = conn.createStatement();
ResultSet rs = aStatement.executeQuery(aQuery);
// Get info about the query results
ResultSetMetaData rsmeta = rs.getMetaData();
int cols = rsmeta.getColumnCount();
// Display column headers
for(int i=1; i<=cols; i++)
{
if(i > 1) System.out.print("\t");
System.out.print(rsmeta.getColumnLabel(i));
}
System.out.print("\n");
// Display query results.
while(rs.next())
{
for(int i=1; i<=cols; i++)
{
if (i > 1) System.out.print("\t");
System.out.print(rs.getString(i));
}
System.out.print("\n");
}
// Clean up
rs.close();
aStatement.close();
conn.close();
}
// a better exception handling can be used here.
catch (Exception e)
{
System.out.println("Exception Occurs.");
}
}
}
import java.sql.*;
public class NewJDBC
{
// 試著將以下的設定以 properties 的檔案讀進來
static String classname = "sun.jdbc.odbc.JdbcOdbcDriver";
static String jdbcURL = "jdbc:odbc:dbms";
static String UID = "uid";
static String PWD = "pwd";
static Connection conn = null;
public static void main( String argv[] )
{
// initialize query string
if(argv.length != 1)
{
System.out.println("Usage: java NewJDBC ");
System.out.println(" ex. java NewJDBC department");
System.exit(2);
}
String aQuery = "select * from " + argv[0];
String iSQL = "insert into " + argv[0] + " values('資訊管理',3,'456789111','12/30/2000')";
String uSQL = "update " + argv[0] + " set dname='資訊工程' where dnumber=3";
String dSQL = "delete " + argv[0] + " where dnumber=3";
try
{
// load the JDBC-ODBC bridge driver
Class.forName(classname);
// connect to Database
conn = DriverManager.getConnection(jdbcURL,UID,PWD);
// Display current content
System.out.println("Display current content");
ShowResults(aQuery);
// Insert a new record
System.out.println("\nInserting a new record .....");
InsertNew(iSQL);
ShowResults(aQuery);
// Update record
System.out.println("\nUpdateing a record .....");
UpdateNew(uSQL);
ShowResults(aQuery);
// Delete record
System.out.println("\nDeleting a record .....");
DeleteNew(dSQL);
ShowResults(aQuery);
conn.close();
} catch (Exception sqle)
{
System.out.println(sqle);
System.exit(1);
}
}
private static void DeleteNew(String dSQL)
{
try
{
Statement aStatement = conn.createStatement();
aStatement.executeUpdate(dSQL);
}
catch (Exception e)
{
System.out.println("Delete Error: " + e);
System.exit(1);
}
}
private static void UpdateNew(String uSQL)
{
try
{
Statement aStatement = conn.createStatement();
aStatement.executeUpdate(uSQL);
}
catch (Exception e)
{
System.out.println("Update Error: " + e);
System.exit(1);
}
}
private static void InsertNew(String iSQL)
{
try
{
Statement aStatement = conn.createStatement();
aStatement.executeUpdate(iSQL);
}
catch (Exception e)
{
System.out.println("Insert Error: " + e);
System.exit(1);
}
}
private static void ShowResults(String aQuery)
{
try
{
// Construct a SQL statement and submit it
Statement aStatement = conn.createStatement();
ResultSet rs = aStatement.executeQuery(aQuery);
// Get info about the query results
ResultSetMetaData rsmeta = rs.getMetaData();
int cols = rsmeta.getColumnCount();
// Display column headers
for(int i=1; i<=cols; i++)
{
if(i > 1) System.out.print("\t");
System.out.print(rsmeta.getColumnLabel(i));
}
System.out.print("\n");
// Display query results.
while(rs.next())
{
for(int i=1; i<=cols; i++)
{
if (i > 1) System.out.print("\t");
System.out.print(rs.getString(i));
}
System.out.print("\n");
}
// Clean up
rs.close();
aStatement.close();
}
// a better exception handling can be used here.
catch (Exception e)
{
System.out.println("Exception Occurs.");
}
}
}
import java.sql.*;
public class OPLTest
{
public static void main( String argv[] )
{
// initialize query string
String aQuery = null;
Connection conn = null;
int flag = 0;
try
{
// load the JDBC-ODBC bridge driver
Class.forName("openlink.jdbc2.Driver");
if (argv.length == 0)
{
System.out.println("Usage: java OPLTest o1 [o2]");
System.out.println(" o1: pubs, dbms, or bob");
System.out.println(" o2: odbc or empty");
System.exit(1);
}
// connect to Database
if (argv[0].equals("bob"))
{
// to MS Access via odbc
flag++;
aQuery = "select * from books";
conn = DriverManager.getConnection("jdbc:openlink://163.17.3.151/DSN=bob/");
}
if (argv[0].equals("pubs"))
{
flag++;
aQuery = "select * from stores";
if (argv.length ==2 && argv[1].equals("odbc"))
// either way is fine.
conn = DriverManager.getConnection(
//"jdbc:openlink://163.17.28.223/DSN=pubs", "uid", "pwd");
"jdbc:openlink://163.17.28.223/DSN=pubs/UID=uid/PWD=pwd/");
// jdbc:openlink://ODBC is type 1 driver which requires
// opljodbc2.jar
//"jdbc:openlink://ODBC/DSN=pubs/UID=uid/PWD=pwd/");
// jdbc:openlink://UDBC is type 2 driver which requires
// opljudbc2.jar
//"jdbc:openlink://UDBC/DSN=pubs/UID=uid/PWD=pwd/");
else
// DSN-less connection
conn = DriverManager.getConnection("jdbc:openlink://163.17.28.223:5000/SVT=SQLServer 7/DATABASE=pubs/UID=uid/PWD=pwd/FBS=55/Readonly=Y/");
}
if (argv[0].equals("dbms"))
{
flag++;
aQuery = "select * from employee";
if (argv.length ==2 && argv[1].equals("odbc"))
conn = DriverManager.getConnection(
"jdbc:openlink://163.17.11.7/DSN=dbms","uid","pwd");
else
conn = DriverManager.getConnection(
"jdbc:openlink://163.17.11.7:5000/Database=dbms/UID=uid/PWD=pwd/SVT=SQLServer 7/FBS=60/Readonly=Y");
}
if (flag == 0)
{
System.out.println("You define wrong DSN. Only pub, dbms, or bob is allowed.");
System.exit(2);
}
// Construct a SQL statement and submit it
Statement aStatement = conn.createStatement();
ResultSet rs = aStatement.executeQuery(aQuery);
// Get info about the query results
ResultSetMetaData rsmeta = rs.getMetaData();
int cols = rsmeta.getColumnCount();
// Display column headers
for(int i=1; i<=cols; i++)
{
if(i > 1) System.out.print("\t");
System.out.print(rsmeta.getColumnLabel(i));
}
System.out.print("\n");
// Display query results.
while(rs.next())
{
for(int i=1; i<=cols; i++)
{
if (i > 1) System.out.print("\t");
System.out.print(rs.getString(i));
}
System.out.print("\n");
}
// Clean up
rs.close();
aStatement.close();
conn.close();
}
// a better exception handling can be used here.
catch (Exception e)
{
System.out.println("Exception Occurs: " + e);
}
}
}
//
// Example JDBC Applet
//
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class OdbcJdbc extends JApplet implements ActionListener
{
private String classname = "sun.jdbc.odbc.JdbcOdbcDriver";
private String jdbcURL = "jdbc:odbc:dbms";
private String UID = "UID";
private String PWD = "PWD";
private Connection conn = null;
private JLabel prompt;
private JTextField input;
private JTextArea outputArea;
private String aQuery = "select * from department";
public void init()
{
// create visual presentation
JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.LEFT));
prompt = new JLabel("Table Name");
input = new JTextField(aQuery, 20);
p.add(prompt);
p.add(input);
outputArea = new JTextArea( 10, 30 );
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add("North", p);
c.add("Center", new JScrollPane(outputArea));
// register event handler
input.addActionListener(this);
}
public void actionPerformed( ActionEvent ev )
{
String text = ev.getActionCommand();
outputArea.setText("");
// Loading JDBC driver
try {
Class.forName(classname);
} catch (Exception e) {
outputArea.append("Loading JDBC error!\n");
outputArea.append(e.toString());
outputArea.append("\n");
}
try {
// connect to Database
conn = DriverManager.getConnection(jdbcURL,UID,PWD);
} catch (SQLException sqle) {
outputArea.append("Connection to database error!\n");
}
showResults(text);
try {
conn.close();
} catch (Exception ex) {
outputArea.append("Connection close error.\n");
}
}
private void showResults(String aQuery)
{
try {
// Construct a SQL statement and submit it
Statement aStatement = conn.createStatement();
ResultSet rs = aStatement.executeQuery(aQuery);
// Get info about the query results
ResultSetMetaData rsmeta = rs.getMetaData();
int cols = rsmeta.getColumnCount();
// Display column headers
for(int i=1; i<=cols; i++)
{
if(i > 1) outputArea.append("\t");
outputArea.append(rsmeta.getColumnLabel(i));
}
outputArea.append("\n");
// Display query results.
while(rs.next())
{
for(int i=1; i<=cols; i++)
{
if (i > 1) outputArea.append("\t");
outputArea.append(rs.getString(i));
}
outputArea.append("\n");
}
// Clean up
rs.close();
aStatement.close();
}
// a better exception handling can be used here.
catch (Exception e) {
outputArea.append("Query error!!\n");
}
}
}
Can't find Database driver class: java.security.AccessControlException: access denied (java.lang.RuntimePermission accessClassInPackage.sun.jdbc.odbc)在以下的範例中,我們在 web server 上也安裝了資料庫(我們用 Oracle 8i),
<applet codebase="." archive="classes111.zip" code="JdbcApplet" width=500 height=200> </applet>
// Import the JDBC classes
import java.sql.*;
// Import the java classes used in applets
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class JdbcApplet extends JApplet implements ActionListener
{
// The connect string
static final String connect_string =
"jdbc:oracle:thin:@hostname:1521:ora";
// The query we will execute
static final String query = "select * from dept";
// The button to push for executing the query
JButton execute_button;
// The place where to dump the query result
JTextArea output;
// The connection to the database
Connection conn;
// Create the User Interface
public void init ()
{
Container c = getContentPane();
c.setLayout (new BorderLayout ());
execute_button = new JButton ("Hello JDBC");
c.add ("North", execute_button);
output = new JTextArea (10, 60);
c.add ("Center", new JScrollPane(output));
execute_button.addActionListener(this);
}
// Do the work
public void actionPerformed (ActionEvent ev)
{
try
{
// See if we need to open the connection to the database
if (conn == null)
{
// Load the JDBC driver
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
// Connect to the databse
output.append("Connecting to " + connect_string + "\n");
conn = DriverManager.getConnection(connect_string, "UID", "PWD");
output.append ("Connected\n");
}
// Create a statement
Statement stmt = conn.createStatement ();
// Execute the query
output.append ("Executing query " + query + "\n");
ResultSet rset = stmt.executeQuery (query);
// Dump the result
while (rset.next ())
{
output.append (rset.getString (1) + "\t");
output.append (rset.getString (2) + "\t");
output.append (rset.getString (3) + "\n");
}
// We're done
output.append ("done.\n");
}
catch (Exception e)
{
// Oops
output.append (e.getMessage () + "\n");
}
}
}
import java.sql.*;
public class JdbcExcel
{
static String classname = "sun.jdbc.odbc.JdbcOdbcDriver";
static String jdbcURL = "jdbc:odbc:grades";
static String UID = "";
static String PWD = "";
static Connection conn = null;
public static void main( String argv[] )
{
// initialize query string
if(argv.length != 1)
{
System.out.println("Usage: java JdbcExcel ");
System.out.println(" ex. java JdbcExcel A");
System.exit(2);
}
String aQuery = "select * from [" + argv[0] + "$]";
try
{
// load the JDBC-ODBC bridge driver
Class.forName(classname);
// connect to Database
conn = DriverManager.getConnection(jdbcURL,UID,PWD);
// Display current content
System.out.println("Display current content");
ShowResults(aQuery);
conn.close();
} catch (Exception sqle)
{
System.out.println(sqle);
System.exit(1);
}
}
private static void ShowResults(String aQuery)
{
try
{
// Construct a SQL statement and submit it
Statement aStatement = conn.createStatement();
ResultSet rs = aStatement.executeQuery(aQuery);
// Get info about the query results
ResultSetMetaData rsmeta = rs.getMetaData();
int cols = rsmeta.getColumnCount();
// Display column headers
for(int i=1; i<=cols; i++)
{
if(i > 1) System.out.print("\t");
System.out.print(rsmeta.getColumnLabel(i));
}
System.out.print("\n");
// Display query results.
while(rs.next())
{
for(int i=1; i<=cols; i++)
{
if (i > 1) System.out.print("\t");
System.out.print(rs.getString(i));
}
System.out.print("\n");
}
// Clean up
rs.close();
aStatement.close();
}
// a better exception handling can be used here.
catch (Exception e)
{
System.out.println("Exception Occurs.");
}
}
}
import java.io.*;
import java.text.*;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hssf.usermodel.*;
public class TestExcel {
public static void main(String[] args) {
DecimalFormat f = new DecimalFormat("###");
try {
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream("ds93f.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
int i = 0;
short col = (short) (sheet.getRow(0).getLastCellNum() - 1);
while((row = sheet.getRow(i)) != null) {
HSSFCell cell;
if(i != 0 &&
row.getCell((short)0).getCellType() == HSSFCell.CELL_TYPE_BLANK)
break;
for(short j = 2; j < col; j++) {
cell = row.getCell(j);
int status = cell.getCellType();
switch (status) {
case HSSFCell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case HSSFCell.CELL_TYPE_NUMERIC:
System.out.print(f.format(cell.getNumericCellValue()) + "\t");
break;
case HSSFCell.CELL_TYPE_FORMULA:
System.out.print(f.format(cell.getNumericCellValue()) + "\t");
break;
case HSSFCell.CELL_TYPE_BLANK:
System.out.print("\t");
break;
default:
System.out.print("unknown type \t");
}
}
System.out.println("");
i++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}