Using JDBC to connect to the database, fly is divided into three steps:
The first step: Download a JDBC driver, then throw the jar package into the project and add to build path;
Step two: Go to the local Oracle folder to find "TNSNames." ORA "file, open the connection string to locate the corresponding database, as the connection string for JDBC;
Step three: Write code to connect to the database through JDBC.
From the Internet to find a section of code, made the next modification. The following is a query of all the fields and field value types in a database table, traversing all the data in the database table (where xxx is the information that needs to be replaced):
Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;ImportJava.sql.ResultSetMetaData; Public classConnectdb { Public Static voidMain (string[] args) {connectdb (); } Public Static voidConnectdb () {Connection con=NULL; PreparedStatement Pre=NULL; ResultSet Results=NULL; ResultSetMetaData ResultSetMetaData=NULL; Try{class.forname ("Oracle.jdbc.driver.OracleDriver"); System.out.println ("Start trying to connect to the database!" "); //You must use the connection string configured in the "Tnsnames.ora" configuration file under the Oracle folder to connect to the database remotelyString url = "jdbc:oracle:" + "thin:@ (DESCRIPTION =" + "(address_list =" + "(ADDRESS = (PROTOCOL = TCP) (HOST = XXX) (PORT = xxx)) " + ")" + "(Connect_data =" + "(service_name = XXX)" + ")" + ")"; String User= "XXX"; String Password= "XXX"; Con=drivermanager.getconnection (URL, user, password); System.out.println ("The connection was successful!" "); String SQL= "SELECT * from XXX"; Pre=con.preparestatement (SQL); System.out.println ("Start executing SQL statements!" "); Results=Pre.executequery (); ResultSetMetaData=Results.getmetadata (); intColumnCount =Resultsetmetadata.getcolumncount (); //Get database table all field names and field value types for(inti = 1; I <= ColumnCount; i++) {System.out.println (Resultsetmetadata.getcolumnname (i)+ ":" +Resultsetmetadata.getcolumntypename (i)); } while(Results.next ()) { for(inti = 1; I <= ColumnCount; i++) {System.out.print (results.getstring (i)+ "\t\t"); } System.out.println (); } } Catch(Exception e) {e.printstacktrace (); } finally { Try { if(Results! =NULL) Results.close (); if(Pre! =NULL) Pre.close (); if(Con! =NULL) Con.close (); System.out.println ("The database connection is closed!" "); } Catch(Exception e) {e.printstacktrace (); } } }}
Connecting the Oracle database through JDBC in Java