Copy Code code 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.executequery (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.executeupdate ();
}
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 ();
}
}
}