我是一个Java爱好者
分类: Oracle
2009-07-13 12:53:05
private java.sql.Connection getOracleConnection()
{
try
{
// A. 注册 Oracle JDBC 驱动程序
Class.forName("oracle.jdbc.driver.OracleDriver");
// B. 创建新数据库连接
conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:flow", "debug" ,"debug");
if(conn!=null) System.out.println("Oracle Connection Successful!");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Error Oracle Trace in getConnection() : " + e.getMessage());
}
return conn;
}
private void closeSQLServerConnection()
{
try
{
if(con!=null)
con.close();
con=null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void closeOracleConnection()
{
try
{
if(conn!=null)
conn.close();
conn=null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void displayDbProperties()
{
java.sql.DatabaseMetaData dm = null;
String InsertStatement ="";
try
{
con = this.getConnection();
conn = this.getOracleConnection();
if(con!=null && conn!=null)
{
// C. 创建 Statement 对象
Statement stmt = con.createStatement();
Statement stmtOracle = conn.createStatement();
// D. 执行 SELECT 命令,查询结果存放在 ResultSet 对象中
ResultSet rset = stmt.executeQuery("SELECT * FROM POLEINFO");
// E. 取得 ResultSet 结果集相关的信息
ResultSetMetaData md = rset.getMetaData();
// F. 取得 ResultSet 对象中的字段数量
int no_cols = md.getColumnCount();
String[] col_names = new String[no_cols];
// G. 取得 ResultSet 对象中各字段名称
for (int i = 0; i < no_cols; i++)
col_names[i] = md.getColumnLabel(i+1);
// H. 先打印出各字段名称
for (int i = 0; i < no_cols; i++)
System.out.print(col_names[i]+"\t");
System.out.println("\n---------------------------------------");
// I. 打印每笔数据列中各字段数据
while (rset.next())
{
/*for (int i = 1; i <= no_cols; i++)
System.out.print(rset.getString(i) + "\t");
System.out.println("");*/
// J. 数据插入 Oracle 中
InsertStatement = "INSERT INTO POLEINFO VALUES ("+rset.getString(1) + ",'" + rset.getString(2) + "','" +
rset.getString(3) + "','" + rset.getString(4)+ "','" + rset.getString(5)+ "','" + rset.getString(6)+ "')";
//注意 "'" 的应用,number类型没有 "'" ,varchar 用
System.out.print(InsertStatement+"\n");
stmtOracle.executeUpdate(InsertStatement);
}
rset.close();
rset = null;
stmt.close();
closeSQLServerConnection();
closeOracleConnection();
}
else
System.out.println("Error: No active Connection");
}
catch(Exception e)
{
e.printStackTrace();
}
dm=null;
}
public static void main(String[] args)
{
try
{
Regionalism regionalism = new Regionalism();
regionalism.displayDbProperties();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}