??xml version="1.0" encoding="utf-8" standalone="yes"?> What is covariant return type? --What an I/O filter? --How can I investigate the physical structure of a database? How can I investigate the parameters to send into and receive from a database stored procedure? How do I check what table-like database objects (table, view, temporary table, alias) are present in a particular database? --How can I connect from an applet to a database on the server? Similarities:
--Question:
java.util.regex是一个用正则表达式所订制的模式来对字W串q行匚w工作的类库包?br>
它包括两个类QPattern和Matcher Pattern 一个Pattern是一个正则表辑ּl编译后的表现模式?
Matcher 一个Matcher对象是一个状态机器,它依据Pattern对象做ؓ匚w模式对字W串展开匚w查?
首先一个Pattern实例订制了一个所用语法与PERL的类似的正则表达式经~译后的模式Q然后一个Matcher实例在这个给定的Pattern实例的模式控制下q行字符串的匚w工作?br>
以下我们分别来看看q两个类Q?br>
2.Patternc?
Pattern的方法如下: static Pattern compile(String regex)
给定的正则表达式编译ƈ赋予lPatternc?
static Pattern compile(String regex, int flags)
同上Q但增加flag参数的指定,可选的flag参数包括QCASE INSENSITIVE,MULTILINE,DOTALL,UNICODE CASEQ?CANON EQ
int flags()
q回当前Pattern的匹配flag参数.
Matcher matcher(CharSequence input)
生成一个给定命名的Matcher对象
static boolean matches(String regex, CharSequence input)
~译l定的正则表辑ּq且对输入的字串以该正则表达式ؓ模开展匹?该方法适合于该正则表达式只会用一ơ的情况Q也是只进行一ơ匹配工作,因ؓq种情况下ƈ不需要生成一个Matcher实例?
String pattern()
q回该Patter对象所~译的正则表辑ּ?
String[] split(CharSequence input)
目标字W串按照Pattern里所包含的正则表辑ּ为模q行分割?
String[] split(CharSequence input, int limit)
作用同上Q增加参数l(f)imit目的在于要指定分割的D|Q如limi设ؓ2Q那么目标字W串根据正则表辑ּ分ؓ割ؓ两段?
一个正则表辑ּQ也是一串有特定意义的字W,必须首先要编译成Z个Patterncȝ实例Q这个Pattern对象会使用matcher()Ҏ(gu)?生成一个Matcher实例Q接着便可以用该 Matcher实例以编译的正则表达式ؓ基础对目标字W串q行匚w工作Q多个Matcher是可以共用一个Pattern对象的?br>
现在我们先来看一个简单的例子Q再通过分析它来了解怎样生成一个Pattern对象q且~译一个正则表辑ּQ最后根据这个正则表辑ּ目标字W串q行分割Q?
import java.util.regex.*;
public class Replacement{
public static void main(String[] args) throws Exception {
// 生成一个Pattern,同时~译一个正则表辑ּ
Pattern p = Pattern.compile("[/]+");
//用Pattern的split()Ҏ(gu)把字W串?/"分割
String[] result = p.split(
"Kevin has seen《LEON》seveal times,because it is a good film."
+"/ 凯文已经看过《这个杀手不太冷》几ơ了Q因为它是一?
+"好电(sh)影?名词:凯文?);
for (int i=0; i
System.out.println(result[i]);
}
}
输出l果为:
Kevin has seen《LEON》seveal times,because it is a good film.
凯文已经看过《这个杀手不太冷》几ơ了Q因为它是一部好?sh)媄?br>名词:凯文?br>
很明显,该程序将字符串按"/"q行了分D,我们以下再?split(CharSequence input, int limit)Ҏ(gu)来指定分D늚D|Q程序改动ؓQ?br>tring[] result = p.split("Kevin has seen《LEON》seveal times,because it is a good film./ 凯文已经看过《这个杀手不太冷》几ơ了Q因为它是一部好?sh)媄?名词:凯文?Q?);
q里面的参数"2"表明目标语句分ZDc?br>
输出l果则ؓQ?
Kevin has seen《LEON》seveal times,because it is a good film.
凯文已经看过《这个杀手不太冷》几ơ了Q因为它是一部好?sh)媄?名词:凯文?br>
׃面的例子Q我们可以比较出java.util.regex包在构造Pattern对象以及~译指定的正则表辑ּ的实现手法与我们在上一中所介绍?Jakarta-ORO 包在完成同样工作时的差别QJakarta-ORO 包要先构造一个PatternCompilercd象接着生成一个Pattern对象Q再正则表辑ּ用该PatternCompilercȝ compile()Ҏ(gu)来将所需的正则表辑ּ~译赋予Patternc:
PatternCompiler orocom=new Perl5Compiler();
Pattern pattern=orocom.compile("REGULAR EXPRESSIONS");
PatternMatcher matcher=new Perl5Matcher();
但是在java.util.regex包里Q我们仅需生成一个Patternc,直接使用它的compile()Ҏ(gu)可以达到同L效果:
Pattern p = Pattern.compile("[/]+");
因此gjava.util.regex的构造法比Jakarta-ORO更ؓzƈҎ(gu)理解?br>
3.Matcherc?
MatcherҎ(gu)如下Q?Matcher appendReplacement(StringBuffer sb, String replacement)
当前匹配子串替换ؓ指定字符Ԍq且替换后的子串以及其之前Cơ匹配子串之后的字符串段dC个StringBuffer对象里?
StringBuffer appendTail(StringBuffer sb)
最后一ơ匹配工作后剩余的字W串dC个StringBuffer对象里?
int end()
q回当前匚w的子串的最后一个字W在原目标字W串中的索引位置 ?
int end(int group)
q回与匹配模式里指定的组相匹配的子串最后一个字W的位置?
boolean find()
试在目标字W串里查找下一个匹配子丌Ӏ?
boolean find(int start)
重设Matcher对象Qƈ且尝试在目标字符串里从指定的位置开始查找下一个匹配的子串?
String group()
q回当前查找而获得的与组匚w的所有子串内?
String group(int group)
q回当前查找而获得的与指定的l匹配的子串内容
int groupCount()
q回当前查找所获得的匹配组的数量?
boolean lookingAt()
目标字W串是否以匹配的子串起始?
boolean matches()
试Ҏ(gu)个目标字W展开匚w,也就是只有整个目标字W串完全匚w时才q回真倹{?
Pattern pattern()
q回该Matcher对象的现有匹配模式,也就是对应的Pattern 对象?
String replaceAll(String replacement)
目标字W串里与既有模式相匹配的子串全部替换为指定的字符丌Ӏ?
String replaceFirst(String replacement)
目标字W串里第一个与既有模式相匹配的子串替换为指定的字符丌Ӏ?
Matcher reset()
重设该Matcher对象?
Matcher reset(CharSequence input)
重设该Matcher对象q且指定一个新的目标字W串?
int start()
q回当前查找所获子串的开始字W在原目标字W串中的位置?
int start(int group)
q回当前查找所获得的和指定l匹配的子串的第一个字W在原目标字W串中的位置?
Q光看方法的解释是不是很不好理解Q不要急,待会l合例子比较容易明白了Q?br>
一个Matcher实例是被用来对目标字W串q行Z既有模式Q也是一个给定的Pattern所~译的正则表辑ּQ进行匹配查扄Q所有往 Matcher的输入都是通过CharSequence接口提供的,q样做的目的在于可以支持对从多元化的数据源所提供的数据进行匹配工作?br>
我们分别来看看各Ҏ(gu)的用:
★matches()/lookingAt ()/find()Q?br>一个Matcher对象是由一个Pattern对象调用其matcher()Ҏ(gu)而生成的Q一旦该Matcher对象生成,它就可以q行三种不同的匹配查找操作:
matches()Ҏ(gu)试Ҏ(gu)个目标字W展开匚w,也就是只有整个目标字W串完全匚w时才q回真倹{?
lookingAt ()Ҏ(gu)检目标字W串是否以匹配的子串起始?
find()Ҏ(gu)试在目标字W串里查找下一个匹配子丌Ӏ?br>
以上三个Ҏ(gu)都将q回一个布?yu)值来表明成功与否?br>
★replaceAll ()/appendReplacement()/appendTail()Q?br>Matchercd时提供了四个匹配子串替换成指定字符串的Ҏ(gu)Q?
replaceAll()
replaceFirst()
appendReplacement()
appendTail()
replaceAll()与replaceFirst()的用法都比较单,L上面Ҏ(gu)的解释。我们主要重点了解一下appendReplacement()和appendTail()Ҏ(gu)?br>
appendReplacement(StringBuffer sb, String replacement) 当前匹配子串替换ؓ指定字符Ԍq且替换后的子串以及其之前Cơ匹配子串之后的字符串段dC个StringBuffer对象里,?appendTail(StringBuffer sb) Ҏ(gu)则将最后一ơ匹配工作后剩余的字W串dC个StringBuffer对象里?br>
例如Q有字符串fatcatfatcatfat,假设既有正则表达式模式ؓ"cat"Q第一ơ匹配后调用appendReplacement(sb, "dog"),那么q时StringBuffer sb的内容ؓfatdogQ也是fatcat中的cat被替换ؓdogq且与匹配子串前的内容加到sb里,而第二次匚w后调?appendReplacement(sb,"dog")Q那么sb的内容就变ؓfatdogfatdogQ如果最后再调用一ơappendTail QsbQ?那么sb最l的内容是fatdogfatdogfat?br>
q是有点模糊Q那么我们来看个单的E序Q?
//该例把句子里的"Kelvin"改ؓ"Kevin"
import java.util.regex.*;
public class MatcherTest{
public static void main(String[] args)
throws Exception {
//生成Pattern对象q且~译一个简单的正则表达?Kelvin"
Pattern p = Pattern.compile("Kevin");
//用Patterncȝmatcher()Ҏ(gu)生成一个Matcher对象
Matcher m = p.matcher("Kelvin Li and Kelvin Chan are both working in Kelvin Chens KelvinSoftShop company");
StringBuffer sb = new StringBuffer();
int i=0;
//使用find()Ҏ(gu)查找W一个匹配的对象
boolean result = m.find();
//使用循环句子里所有的kelvin扑ևq替换再内容加到sb?br>while(result) {
i++;
m.appendReplacement(sb, "Kevin");
System.out.println("W?+i+"ơ匹配后sb的内Ҏ(gu)Q?+sb);
//l箋查找下一个匹配对?br>result = m.find();
}
//最后调用appendTail()Ҏ(gu)最后一ơ匹配后的剩余字W串加到sb里;
m.appendTail(sb);
System.out.println("调用m.appendTail(sb)后sb的最l内Ҏ(gu):"+ sb.toString());
}
}
最l输出结果ؓQ?br>W?ơ匹配后sb的内Ҏ(gu)QKevin
W?ơ匹配后sb的内Ҏ(gu)QKevin Li and Kevin
W?ơ匹配后sb的内Ҏ(gu)QKevin Li and Kevin Chan are both working in Kevin
W?ơ匹配后sb的内Ҏ(gu)QKevin Li and Kevin Chan are both working in Kevin Chens Kevin
调用m.appendTail(sb)后sb的最l内Ҏ(gu)QKevin Li and Kevin Chan are both working in Kevin Chens KevinSoftShop company.
看了上面q个例程是否对appendReplacement()QappendTail()两个Ҏ(gu)的用更清楚呢,如果q是不太肯定最好自己动手写几行代码试一下?br>
★group()/group(int group)/groupCount()Q?br>该系列方法与我们在上介l的Jakarta-ORO中的MatchResult .group()Ҏ(gu)cM(有关Jakarta-ORO请参考上的内容)Q都是要q回与组匚w的子串内容,下面代码很好解释其用法Q?
import java.util.regex.*;
public class GroupTest{
public static void main(String[] args)
throws Exception {
Pattern p = Pattern.compile("(ca)(t)");
Matcher m = p.matcher("one cat,two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
System.out.println("该次查找获得匚wl的数量为:"+m.groupCount());
for(int i=1;i<=m
}
}
输出为:
该次查找获得匚wl的数量为:2
W?l的子串内容为:ca
W?l的子串内容为:t
Matcher对象的其他方法因比较好理解且׃幅有限Q请读者自qE验证?br>
4Q一个检验Email地址的小E序Q?
最后我们来看一个检验Email地址的例E,该程序是用来验一个输入的EMAIL地址里所包含的字W是否合法,虽然q不是一个完整的EMAIL地址验程序,它不能检验所有可能出现的情况Q但在必要时(zhn)可以在其基上增加所需功能?
import java.util.regex.*;
public class Email {
public static void main(String[] args) throws Exception {
String input = args[0];
//输入的EMAIL地址是否?非法W号"."?@"作ؓ起始字符
Pattern p = Pattern.compile("^.|^@");
Matcher m = p.matcher(input);
if (m
//是否以"www."v?br>p = Pattern.compile("^www.");
m = p.matcher(input);
if (m
//是否包含非法字W?br>p = Pattern.compile("[^A-Za-z0-9.@_-~#]+");
m = p.matcher(input);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
boolean deletedIllegalChars = false;
while(result) {
//如果扑ֈ了非法字W那么就设下标记
deletedIllegalChars = true;
//如果里面包含非法字符如冒号双引号{,那么把他们消去Q加到SB里面
m.appendReplacement(sb, "");
result = m.find();
}
m.appendTail(sb);
input = sb.toString();
if (deletedIllegalChars) {
System.out.println("输入的EMAIL地址里包含有冒号、逗号{非法字W,请修?);
System.out.println("(zhn)现在的输入? "+args[0]);
System.out.println("修改后合法的地址应类? "+input);
}
}
}
例如Q我们在命o行输入:java Email www.kevin@163.net
那么输出l果会是:EMAIL地址不能以www.起始
如果输入的EMAIL为@kevin@163.net
则输ZؓQEMAIL地址不能?或@作ؓ起始字符
当输入ؓQcgjmail#$%@163.net
那么输出是Q?br>
输入的EMAIL地址里包含有冒号、逗号{非法字W,请修?br>(zhn)现在的输入? cgjmail#$%@163.net
修改后合法的地址应类? cgjmail@163.net
5QȝQ?
本文介绍了jdk1.4.0-beta3里正则表辑ּ?-java.util.regex中的cM及其Ҏ(gu)Q如果结合与上一中所介绍的Jakarta -ORO API作比较,读者会更容易掌握该API的用,当然该库的性能在未来的日子里不断扩展Q希望获得最C息的读者最好到及时到SUN的网站去了解?br>
6Q结束语Q?
本来计划再多写一介l一下需付费的正则表辑ּ库中较具代表性的作品Q但觉得既然有了免费且优U的正则表辑ּ库可以用,何必q要L需付费的呢Q相信很 多读者也是这么想?Q所以有兴趣了解更多其他的第三方正则表达式库的朋友可以自己到|上查找或者到我在参考资料里提供的网址ȝ看?br>
]]>
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
--Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
--How can we make a class Singleton ?
A) If the class is Serializable
class Singleton implements Serializable
{
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
/**
If the singleton implements Serializable, then this method must be supplied.
*/
protected Object readResolve() {
return instance;
}
/**
This method avoids the object fro being cloned
*/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}
B) If the class is NOT Serializable
class Singleton
{
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
/**
This method avoids the object from being cloned**/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}
--
A covariant return type lets you override a superclass method with a return type that subtypes the superclass method's return type. So we can use covariant return types to minimize upcasting and downcasting.
class Parent {
Parent foo () {
System.out.println ("Parent foo() called");
return this;
}
}
class Child extends Parent {
Child foo () {
System.out.println ("Child foo() called");
return this;
}
}
class Covariant {
public static void main(String[] args) {
Child c = new Child();
Child c2 = c.foo(); // c2 is Child
Parent c3 = c.foo(); // c3 points to Child
}
}
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
--What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
--What is autoboxing ?
Automatic conversion between reference and primitive types.
The JDBC view of a database internal structure can be seen in the image below.
* Several database objects (tables, views, procedures etc.) are contained within a Schema.
* Several schema (user namespaces) are contained within a catalog.
* Several catalogs (database partitions; databases) are contained within a DB server (such as Oracle, MS SQL
The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all Catalogs
System.out.println("\nCatalogs are called '" + dbmd.getCatalogTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());
// Get all Schemas
System.out.println("\nSchemas are called '" + dbmd.getSchemaTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());
// Get all Table-like types
System.out.println("\nAll table types supported in this RDBMS:");
processResultSet("Table type", dbmd.getTableTypes());
// Close the Connection
conn.close();
}
public static void processResultSet(String preamble, ResultSet rs)
throws SQLException
{
// Printout table data
while(rs.next())
{
// Printout
System.out.println(preamble + ": " + rs.getString(1));
}
// Close database resources
rs.close();
}
---How do I find all database stored procedures in a database?
Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all procedures.
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedures(null, null, "%");
// Printout table data
while(rs.next())
{
// Get procedure metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbProcedureRemarks = rs.getString(7);
short dbProcedureType = rs.getShort(8);
// Make result readable for humans
String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");
// Printout
System.out.println("Procedure: " + dbProcedureName + ", returns: " + procReturn);
System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]");
System.out.println(" Comments: " + dbProcedureRemarks);
}
// Close database resources
rs.close();
conn.close();
}
Use the method getProcedureColumns in interface DatabaseMetaData to probe a stored procedure for metadata. The exact usage is described in the code below.
NOTE! This method can only discover parameter values. For databases where a returning ResultSet is created simply by executing a SELECT statement within a stored procedure (thus not sending the return ResultSet to the java application via a declared parameter), the real return value of the stored procedure cannot be detected. This is a weakness for the JDBC metadata mining which is especially present when handling Transact-SQL databases such as those produced by SyBase and Microsoft.
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
;
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all column definitions for procedure "getFoodsEaten" in
// schema "testlogin" and catalog "dbo".
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");
// Printout table data
while(rs.next())
{
// Get procedure metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbColumnName = rs.getString(4);
short dbColumnReturn = rs.getShort(5);
String dbColumnReturnTypeName = rs.getString(7);
int dbColumnPrecision = rs.getInt(8);
int dbColumnByteLength = rs.getInt(9);
short dbColumnScale = rs.getShort(10);
short dbColumnRadix = rs.getShort(11);
String dbColumnRemarks = rs.getString(13);
// Interpret the return type (readable for humans)
String procReturn = null;
switch(dbColumnReturn)
{
case DatabaseMetaData.procedureColumnIn:
procReturn = "In";
break;
case DatabaseMetaData.procedureColumnOut:
procReturn = "Out";
break;
case DatabaseMetaData.procedureColumnInOut:
procReturn = "In/Out";
break;
case DatabaseMetaData.procedureColumnReturn:
procReturn = "return value";
break;
case DatabaseMetaData.procedureColumnResult:
procReturn = "return ResultSet";
default:
procReturn = "Unknown";
}
// Printout
System.out.println("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema
+ "." + dbProcedureName);
System.out.println(" ColumnName [ColumnType(ColumnPrecision)]: " + dbColumnName
+ " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]");
System.out.println(" ColumnReturns: " + procReturn + "(" + dbColumnReturnTypeName + ")");
System.out.println(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale);
System.out.println(" Remarks: " + dbColumnRemarks);
}
// Close database resources
rs.close();
conn.close();
}
Use java.sql.DatabaseMetaData to probe the database for metadata. Use the getTables method to retrieve information about all database objects (i.e. tables, views, system tables, temporary global or local tables or aliases). The exact usage is described in the code below.
NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to access fields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you should not change the order in which you retrieve the metadata from the ResultSet.
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all dbObjects. Replace the last argument in the getTables
// method with objectCategories below to obtain only database
// tables. (Sending in null retrievs all dbObjects).
String[] objectCategories = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", null);
// Printout table data
while(rs.next())
{
// Get dbObject metadata
String dbObjectCatalog = rs.getString(1);
String dbObjectSchema = rs.getString(2);
String dbObjectName = rs.getString(3);
String dbObjectType = rs.getString(4);
// Printout
System.out.println("" + dbObjectType + ": " + dbObjectName);
System.out.println(" Catalog: " + dbObjectCatalog);
System.out.println(" Schema: " + dbObjectSchema);
}
// Close database resources
rs.close();
conn.close();
}
Use the getColumns method of the java.sql.DatabaseMetaData interface to investigate the column type information of a particular table. Note that most arguments to the getColumns method (pinpointing the column in question) may be null, to broaden the search criteria. A code sample can be seen below:
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all column types for the table "sysforeignkeys", in schema
// "dbo" and catalog "test".
ResultSet rs = dbmd.getColumns("test", "dbo", "sysforeignkeys", "%");
// Printout table data
while(rs.next())
{
// Get dbObject metadata
String dbObjectCatalog = rs.getString(1);
String dbObjectSchema = rs.getString(2);
String dbObjectName = rs.getString(3);
String dbColumnName = rs.getString(4);
String dbColumnTypeName = rs.getString(6);
int dbColumnSize = rs.getInt(7);
int dbDecimalDigits = rs.getInt(9);
String dbColumnDefault = rs.getString(13);
int dbOrdinalPosition = rs.getInt(17);
String dbColumnIsNullable = rs.getString(18);
// Printout
System.out.println("Col(" + dbOrdinalPosition + "): " + dbColumnName
+ " (" + dbColumnTypeName +")");
System.out.println(" Nullable: " + dbColumnIsNullable +
", Size: " + dbColumnSize);
System.out.println(" Position in table: " + dbOrdinalPosition
+ ", Decimal digits: " + dbDecimalDigits);
}
// Free database resources
rs.close();
conn.close();
}
---How do I insert an image file (or other raw data) into a database?
All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to upload the data.
There are two ways of connecting to a database on the server side.
1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.
2. The easy way. Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.
---Many connections from an Oracle8i pooled connection returns statement closed. I am using import oracle.jdbc.pool.* with thin driver. If I test with many simultaneous connections, I get an SQLException that the statement is closed.
ere is an example of concurrent operation of pooled connections from the OracleConnectionPoolDataSource. There is an executable for kicking off threads, a DataSource, and the workerThread.
The Executable Member
package package6;
/**
* package6.executableTester
*/
public class executableTester {
protected static myConnectionPoolDataSource dataSource = null;
static int i = 0;
/**
* Constructor
*/
public executableTester() throws java.sql.SQLException
{
}
/**
* main
* @param args
*/
public static void main(String[] args) {
try{
dataSource = new myConnectionPoolDataSource();
}
catch ( Exception ex ){
ex.printStackTrace();
}
while ( i++ < 10 ) {
try{
workerClass worker = new workerClass();
worker.setThreadNumber( i );
worker.setConnectionPoolDataSource( dataSource.getConnectionPoolDataSource() );
worker.start();
System.out.println( "Started Thread#"+i );
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
}
}
The DataSource Member
package package6;
import oracle.jdbc.pool.*;
/**
* package6.myConnectionPoolDataSource.
*
*/
public class myConnectionPoolDataSource extends Object {
protected OracleConnectionPoolDataSource ocpds = null;
/**
* Constructor
*/
public myConnectionPoolDataSource() throws java.sql.SQLException {
// Create a OracleConnectionPoolDataSource instance
ocpds = new OracleConnectionPoolDataSource();
// Set connection parameters
ocpds.setURL("jdbc:oracle:oci8:@mydb");
ocpds.setUser("scott");
ocpds.setPassword("tiger");
}
public OracleConnectionPoolDataSource getConnectionPoolDataSource() {
return ocpds;
}
}
The Worker Thread Member
package package6;
import oracle.jdbc.pool.*;
import java.sql.*;
import javax.sql.*;
/**
* package6.workerClass .
*
*/
public class workerClass extends Thread {
protected OracleConnectionPoolDataSource ocpds = null;
protected PooledConnection pc = null;
protected Connection conn = null;
protected int threadNumber = 0;
/**
* Constructor
*/
public workerClass() {
}
public void doWork( ) throws SQLException {
// Create a pooled connection
pc = ocpds.getPooledConnection();
// Get a Logical connection
conn = pc.getConnection();
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ename from emp");
// Iterate through the result and print the employee names
while (rset.next ())
// System.out.println (rset.getString (1));
;
// Close the RseultSet
rset.close();
rset = null;
// Close the Statement
stmt.close();
stmt = null;
// Close the logical connection
conn.close();
conn = null;
// Close the pooled connection
pc.close();
pc = null;
System.out.println( "workerClass.thread#"+threadNumber+" completed..");
}
public void setThreadNumber( int assignment ){
threadNumber = assignment;
}
public void setConnectionPoolDataSource(OracleConnectionPoolDataSource x){
ocpds = x;
}
public void run() {
try{
doWork();
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
}
The OutPut Produced
Started Thread#1
Started Thread#2
Started Thread#3
Started Thread#4
Started Thread#5
Started Thread#6
Started Thread#7
Started Thread#8
Started Thread#9
Started Thread#10
workerClass.thread# 1 completed..
workerClass.thread# 10 completed..
workerClass.thread# 3 completed..
workerClass.thread# 8 completed..
workerClass.thread# 2 completed..
workerClass.thread# 9 completed..
workerClass.thread# 5 completed..
workerClass.thread# 7 completed..
workerClass.thread# 6 completed..
workerClass.thread# 4 completed..
The oracle.jdbc.pool.OracleConnectionCacheImpl class is another subclass of the oracle.jdbc.pool.OracleDataSource which should also be looked over, that is what you really what to use. Here is a similar example that uses the oracle.jdbc.pool.OracleConnectionCacheImpl. The general construct is the same as the first example but note the differences in workerClass1 where some statements have been commented ( basically a clone of workerClass from previous example ).
The Executable Member
package package6;
import java.sql.*;
import javax.sql.*;
import oracle.jdbc.pool.*;
/**
* package6.executableTester2
*
*/
public class executableTester2 {
static int i = 0;
protected static myOracleConnectCache
connectionCache = null;
/**
* Constructor
*/
public executableTester2() throws SQLException
{
}
/**
* main
* @param args
*/
public static void main(String[] args) {
OracleConnectionPoolDataSource dataSource = null;
try{
dataSource = new OracleConnectionPoolDataSource() ;
connectionCache = new myOracleConnectCache( dataSource );
}
catch ( Exception ex ){
ex.printStackTrace();
}
while ( i++ < 10 ) {
try{
workerClass1 worker = new workerClass1();
worker.setThreadNumber( i );
worker.setConnection( connectionCache.getConnection() );
worker.start();
System.out.println( "Started Thread#"+i );
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
}
protected void finalize(){
try{
connectionCache.close();
} catch ( SQLException x) {
x.printStackTrace();
}
this.finalize();
}
}
The ConnectCacheImpl Member
package package6;
import javax.sql.ConnectionPoolDataSource;
import oracle.jdbc.pool.*;
import oracle.jdbc.driver.*;
import java.sql.*;
import java.sql.SQLException;
/**
* package6.myOracleConnectCache
*
*/
public class myOracleConnectCache extends
OracleConnectionCacheImpl {
/**
* Constructor
*/
public myOracleConnectCache( ConnectionPoolDataSource x)
throws SQLException {
initialize();
}
public void initialize() throws SQLException {
setURL("jdbc:oracle:oci8:@myDB");
setUser("scott");
setPassword("tiger");
//
// prefab 2 connection and only grow to 4 , setting these
// to various values will demo the behavior
//clearly, if it is not
// obvious already
//
setMinLimit(2);
setMaxLimit(4);
}
}
The Worker Thread Member
package package6;
import oracle.jdbc.pool.*;
import java.sql.*;
import javax.sql.*;
/**
* package6.workerClass1
*
*/
public class workerClass1 extends Thread {
// protected OracleConnectionPoolDataSource
ocpds = null;
// protected PooledConnection pc = null;
protected Connection conn = null;
protected int threadNumber = 0;
/**
* Constructor
*/
public workerClass1() {
}
public void doWork( ) throws SQLException {
// Create a pooled connection
// pc = ocpds.getPooledConnection();
// Get a Logical connection
// conn = pc.getConnection();
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery
("select ename from EMP");
// Iterate through the result
// and print the employee names
while (rset.next ())
// System.out.println (rset.getString (1));
;
// Close the RseultSet
rset.close();
rset = null;
// Close the Statement
stmt.close();
stmt = null;
// Close the logical connection
conn.close();
conn = null;
// Close the pooled connection
// pc.close();
// pc = null;
System.out.println( "workerClass1.thread#
"+threadNumber+" completed..");
}
public void setThreadNumber( int assignment ){
threadNumber = assignment;
}
// public void setConnectionPoolDataSource
(OracleConnectionPoolDataSource x){
// ocpds = x;
// }
public void setConnection( Connection assignment ){
conn = assignment;
}
public void run() {
try{
doWork();
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
}
The OutPut Produced
Started Thread#1
Started Thread#2
workerClass1.thread# 1 completed..
workerClass1.thread# 2 completed..
Started Thread#3
Started Thread#4
Started Thread#5
workerClass1.thread# 5 completed..
workerClass1.thread# 4 completed..
workerClass1.thread# 3 completed..
Started Thread#6
Started Thread#7
Started Thread#8
Started Thread#9
workerClass1.thread# 8 completed..
workerClass1.thread# 9 completed..
workerClass1.thread# 6 completed..
workerClass1.thread# 7 completed..
Started Thread#10
workerClass1.thread# 10 completed..
]]>
Answer: Differences are as follows:
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}
--Question: What is Collection API?
Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet
, HashMap
, ArrayList
, LinkedList
, TreeSet
and TreeMap
.
Example of interfaces: Collection
, Set
, List
and Map.
--
Question: Describe the principles of OOPS.
Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Question: Explain the Encapsulation principle.
Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
Question: Explain the Inheritance principle.
Answer: Inheritance is the process by which one object acquires the properties of another object.
Question: Explain the Polymorphism principle.
Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".
Question: Explain the different forms of Polymorphism. --Question: What do you understand by final value?
Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
Answer: FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived.
--Question: How to convert String to Number in java program?
Answer: The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String strId = "10"; int id=Integer.valueOf(strId);