欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个jdbc 测试程序代码

程序员文章站 2023-11-29 08:41:58
复制代码 代码如下:import java.sql.date; import java.sql.connection; import java.sql.preparedst...

复制代码 代码如下:

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();
}
}
}