Copy codeThe Code is as follows:
Import java. SQL. Date;
Import java. SQL. Connection;
Import java. SQL. PreparedStatement;
Import java. SQL. ResultSetMetaData;
Import java. SQL. Statement;
Import java. SQL. ResultSet;
Import java. SQL. DriverManager;
Import java. SQL. SQLException;
Public class FirstOracleJdbc {
Public static void main (String [] args) throws SQLException {
Insert (new int [] {5}, new String [] {"iGoder"}, new Date [] {Date. valueOf ("1980-01-01 ")});
Select ();
}
Public static void select (){
Connection con = null;
Statement st = null;
ResultSet rs = null;
Try {
Class. forName ("oracle. jdbc. driver. OracleDriver ");
Con = DriverManager. getConnection (
"Jdbc: oracle: thin: @ localhost: 1521: xe", "test", "test ");
St = con. createStatement ();
String SQL = "select * from student ";
Rs = st.exe cuteQuery (SQL );
While (rs. next ()){
System. out. print ("id =" + rs. getInt ("id "));
System. out. print (", name =" + rs. getString ("name "));
System. out. print (", birthday =" + rs. getDate ("birthday") + "\ n ");
}
System. out. print ("++ ");
// PrintRS (rs );
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
Try {
Rs. close ();
} Catch (Exception e ){
}
Try {
St. close ();
} Catch (Exception e ){
}
Try {
Con. close ();
} Catch (Exception e ){
}
}
}
Public static void insert (int [] ids, String [] names, Date [] dates)
Throws SQLException {
Connection con = null;
PreparedStatement ps = null;
Try {
Class. forName ("oracle. jdbc. driver. OracleDriver ");
Con = DriverManager. getConnection (
"Jdbc: oracle: thin: @ localhost: 1521: xe", "test", "test ");
Con. setAutoCommit (false );
String SQL = "insert into student (id, name, birthday) values (?,?,?) ";
Ps = con. prepareStatement (SQL );
For (int I = 0; I <ids. length; I ++ ){
Int index = 1;
Ps. setInt (index ++, ids [I]);
Ps. setString (index ++, names [I]);
Ps. setDate (index ++, dates [I]);
Ps.exe cuteUpdate ();
}
Con. commit ();
} Catch (Exception e ){
E. printStackTrace ();
Try {
Con. rollback ();
} Catch (Exception e1 ){
}
Throw new SQLException (e. getMessage ());
} Finally {
Try {
Ps. close ();
} Catch (Exception e ){
}
Try {
Con. close ();
} Catch (Exception e ){
}
}
}
Public static void printRS (ResultSet rs) throws SQLException
{
ResultSetMetaData rsmd = rs. getMetaData ();
Int colCount = rsmd. getColumnCount ();
While (rs. next ())
{
For (int I = 1; I <= colCount; I ++)
{
If (I> 1)
{
System. out. print (",");
}
String name = rsmd. getColumnName (I );
String value = rs. getString (I );
System. out. print (name + "=" + value );
}
System. out. println ();
}
}
}