程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> 一個jdbc 測試程序代碼

一個jdbc 測試程序代碼

編輯:關於JSP

復制代碼 代碼如下:
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();
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved