`
Vitas_Wang
  • 浏览: 9225 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java connection to oracle

    博客分类:
  • java
阅读更多
Register the JDBC drivers:
there have two ways:
Class.forName("oracle.jdbc.OracleDriver");//this method is only valid for JDK-compliant Java virtual machines. 
										  //It is not valid for Microsoft Java virtual machines
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

Open a connection to a database:
										  
1> DriverManager.getConnection(String DB_URL,String DB_USERNAME,String DB_PASSWORD);
Where the URL is of the form:
jdbc:oracle:<drivertype>:@<database>
The following example connects user scott with password tiger to a database with SID orcl through port 1521 of host myhost, using the Thin driver.

Connection conn = DriverManager.getConnection
  ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");

2> DriverManager.getConnection(String DB_URL)
where the URL is of the form:
  jdbc:oracle:<drivertype>:<user>/<password>@<database>
If you want to connect with the Thin driver, you must specify the port number and SID. For example, if you want to connect to the database on host myhost that has a TCP/IP listener up on port 1521,
 and the SID (system identifier) is orcl:
Connection conn = DriverManager.getConnection
   ("jdbc:oracle:thin:scott/tiger@myhost:1521:orcl);

3> getConnection(String URL, Properties info);
Where the URL is of the form:
  jdbc:oracle:<drivertype>:@<database>
In addition to the URL, use an object of the standard Java Properties class as input. For example:

java.util.Properties info = new java.util.Properties();
  info.put ("user", "scott");
  info.put ("password","tiger");
  info.put ("defaultRowPrefetch","15");
  getConnection ("jdbc:oracle:oci8:@",info);

Create an instance of the Java class Statement:

1>Statement stmt=Connection.createStatement();
2>The class PreparedStatement is a subclass of Statement, 
but it pre-compiles the SQL statement before executing it.
PreparedStatement stmt=conn.prepareStatement(
                          " SELECT * from Employee WHERE empno=?");
for (int i=0;i<empNumbers.length; i++){

     // pass the array's value that substitutes the question mark
     stmt.setInt(1,employees[i];)
     stmt.executeQuery(sqlQuery);
   }
3>the callableStatement is used for executing stored procedures from java 
CallableStatement stmt = conn.prepareCall("{call changeEmpTitle(?,?)}");

   stmt.setInt(1,7566);
   stmt.setString (2,"Salesman");
   stmt.executeUpdate();
 If a stored procedure returns some values using output parameters, 
 each of the OUT data types has to be registered before the statement is executed  
 CallableStatement stmt = conn.prepareCall(
                    ("{call getEmpTitle(?,?) }");
   stmt.setInt(1, 7566);
   stmt.registerOutParameter(2,Java.sql.Types.VARCHAR);
   stmt.executeQuery();
   String title=stmt.getString(2);
   
ResultSet:
  1> get the values of each field by specifying the relative position of the column from the reuslt set:
	int empNo = rs.getInt(1);
    String eName = rs.getString(2);
	 
  2> use the field name:
	int empNo = rs.getInt("EMPNO");
    String eName = rs.getString("ENAME");
 ResultSetMetaData:
	with the class ResultSetMetaData you can dynamically find out how many columns three are in the result set
as well as their names and data types 	
 String sqlQuery = "select * from Employee";
   ResultSet rs = stmt.executeQuery(query);

   ResultSetMetaData rsMeta = rs.getMetaData();
   int colCount = rsMeta.getColumnCount();

   for (int i = 1; i <= colCount; i++) {
     System.out.println(
         " Column name: " + rsMeta.getColumnName(i) +
         " Column type: " + rsMeta.getColumnTypeName(i));
   }

补充:现在有些连接直接提供的是service_name,而不是sid,这种情况下地URL格式为
jdbc:oracle:<driver_type>:@//<database>:<port>/<service_name>
下面是一段可执行代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;


public class OracleConnectionDemo {
	private final static String DB_URL = "jdbc:oracle:thin:@17.26.66.209:5731:PDS";
	private final static String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private final static String DB_USERNAME = "scott";
	private final static String DB_PASSWORD = "tiger";
	public static void main(String[] args){
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement stmt1 = null;
		ResultSet rs = null;
		ResultSetMetaData reMeta = null;
		String querysql = "select nda_id from test where rownum < 5";
		try{
			//Load the JDBC driver using the method forName()
			Class.forName(DB_DRIVER);
			
			//Obtain the database connection to database
			conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
			//conn = DriverManager.getConnection(DB_URL1);
			//Create an instance of the java class statement:
			stmt = conn.createStatement();
			rs = stmt.executeQuery(querysql);
			while(rs.next()){
				int nda_id = rs.getInt("nda_id");
				System.out.println(nda_id);
			}
			rs.close();
			stmt1 = conn.prepareStatement("select * from test where nda_id = ?");
			stmt1.setInt(1, 16117);
			rs = stmt1.executeQuery();
			reMeta = rs.getMetaData();
			int columCount = reMeta.getColumnCount();
			for(int i = 1; i <= columCount; i++){
				System.out.print("Column name: " + reMeta.getColumnName(i));
				System.out.println(" Column type: " + reMeta.getColumnTypeName(i));
			}
			while(rs.next()){
				System.out.println(rs.getInt(2));
			}
		} catch(SQLException se){
			System.out.println("SQLError: " + se.getMessage() + "code: " + se.getErrorCode());
		} catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally{
				try {
				rs.close();
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

分享到:
评论

相关推荐

    java7帮助文档

    The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement; see Closing Connections in Processing SQL Statements. RowSet 1.1: The ...

    Oracle WebLogic Server 10gR3: Troubleshooting Methodologies

    Review: JDBC Database, Datasources, Connection Pool, and Statement Cache Investigating JDBC Problems Server Startup: Failed Pool Creation Causes of Resource Exceptions Overview of Insufficient ...

    最完整的Toad For Oracle使用手册

    Connecting to Oracle 97 Server Login Window 97 Create New Connection 99 Selecting Connection Color 101 SET ROLE 101 Auto Connect 103 Save Passwords for Connections 104 Select and View Favorite ...

    利用 Oracle 和 PHP 管理分布式跟踪文件

    Trace File Manager (TFM) - Using PHP and Oracle to manage your ...there may well be a fundamental problem with your java layer.Apahe / PHP layer If you haven‘t already done so, deploy Apache and ...

    Practical Database Programming with Java

    JavaServer Pages, JavaServer Faces, and Enterprise Java Beans, are discussed and analyzed with real projects to enable readers to have a clear picture and easy-to-learn path for Java database ...

    JDBC Developers Guide Reference.rar

    This chapter covers the Oracle extensions to the JDBC standard that let you access and manipulate LOBs and LOB data. Chapter 8, "Working with Oracle Object Types" This chapter explains how to map ...

    swingbench2.6.1124.zip

    * Support for remote connectivity to Oracle Cloud in connection dialogues * New "SBUtil" (Swingbench Utility) to validate benchmarks and scale them up (SH and OE Only at present) * New "results2pdf" ...

    linux系统安装oracle数据库详解

    #Xlib: connection to ":0.0" refused by server Xlib: No protocol specified 错误三 warning: Cannot convert string "-isas-song ti-medium-r-normal--*-140-*-*-c-*-gb2312.1980-0" to type 错误四 Checking ...

    Java连接Oralce数据库小例

    System.out.println("Now begin to excute............."); // 查询 List[]&gt; rslist = new ArrayList[]&gt;(); ResultSet newrs = dbfuns .executeQuery("select * from emp order by empno"); ...

    Spring and iBATIS

    JAVA JDBC is a low level API, and thus several attempts to enhance it in various aspects have been mad such as EJB, JDO, Hibernate, Toplink(from Oracle), iBATIS, SQLExecutor, and Spring JDBC support ...

    hibernate.properties

    #hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver #hibernate.connection.username ora #hibernate.connection.password ora #hibernate.connection.url jdbc:oracle:thin:@localhost:1521:orcl...

    java面试宝典

    196、Can a database connection pool be instantiated in init method of servlet instead of server connection pool? What will be the problem? 46 综合部分 46 197、Class.forName的作用?为什么要用? 47 198、...

    jdbc连接数据库的方式2

    MySQL目前提供的java驱动程序为Connection/J,可以从MySQL官方网站下载,并找到mysql-connector-java-3.0.15-ga-bin.jar文件,此驱动程序为纯java驱动程序,不需做其他配置。 2、动态指定classpath 如果需要执行...

    Pro HTML5 Programming(HTML5高级程序设计英文原版)

    but also a socket, native to the browser, that facilitates network programming from the browser with efficient bidirectional (full-duplex) communication over a single connection. * Explains how you...

    ZeosDBO

    4.1PostgreSQL 6.5 - 7.4Firebird 1.0 - 1.5Interbase 5.0 - 7.5Microsoft SQL Server 7, 2000Sybase ASE 12.0, 12.5Oracle 9iSQLite 2.8For other databases we propose to use implemented Active Data Objects ...

    破解版mdbdriver.jar

    最近刚好有个项目要连接ACCESS的MDB数据并导入到ORACLE中,使用 Java代码 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String strurl="jdbc:odbc:driver={Microsoft Access Driver(*.mdb)};DBQ=E:\\\\db.mdb...

    jdbc基础和参考

    many-to-one:标签中对于cascade的取值delete,delete-orphan,all-delete-orphan(只用unique属性值不为true不能出现)慎用 cascade:级联属性 none:不做任何级联操作 save-update:对当前对象执行save,update, ...

    jive.chm

    4 Jive的中文问题及解决办法 5 Java程序的国际化和本地化介绍 6 Java的i18n问题 7 Java国际化——资源包的使用 8 国际化 9 Supported Encodings 10 native2ascii - Native-to-...

    千方百计笔试题大全

    196、Can a database connection pool be instantiated in init method of servlet instead of server connection pool? What will be the problem? 46 综合部分 46 197、Class.forName的作用?为什么要用? 47 198、...

    Loadrunner报错日志

    Java连接池的大小设置,或JVM的设置等 3&gt;数据库的连接 在应用服务的性能参数可能太小了 数据库启动的最大连接数(跟硬件的内存有关) 以上信息有一定的参考价值,实际情况可以参考此类调试。 如果是以上所说的小用户...

Global site tag (gtag.js) - Google Analytics