Java调用Oracle数据库的步骤
Java代码向数据库中添加数据有四步
代码不是关键,重要的是记住这四个步骤。
第一步:加载驱动
try {
Class.forName("oracle.jdbc.OracleDriver");// 加载Oracle驱动
Class.forName("com.mysql.cj.jdbc.Driver");// 加载Mysql驱动
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败。");
e.printStackTrace();
}
第二步:连接数据库
Connection coon = null;
//创建连接;
url:连接串:jdbc:oracle:thin:@127.0.0.1[:8080:xe
try {
//@后面的IP根据自己的数据库地址写,这里给出格式。
coon = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:8080:数据库名称", "用户名", "密码");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接数据库失败。。。。。。。");
e.printStackTrace();
}
第三步:创建PrepareStatement对象
PreparedStatement p = null;
try {
StringBuffer a = new StringBuffer();
for(int i=0; i<list.size(); i++){
String CreatBy = "Lothar";
String CreatDate = "2019/05/24"
a.append("+CreatedBy+");
a.append(", to_date('"+CreationDate+"','yyyy-mm-dd')"+")");
}
p = coon.prepareStatement("insert into a_Table(CREAT_BY,CREAT_DATE) values"+a);
p.executeUpdate();//表示执行PreparedStatement 中封装的sql语句
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("PreparedStatement 对象创建失败 。");
e.printStackTrace();
}
第四步:关闭资源
if(coon!=null&&p!=null){}
try {
coon.close();
p.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}