JDBC访问数据库的基本步骤

 A.载入JDBC驱动程序

String driver = "oracle.jdbc.driver.OracleDriver";

B.定义连接URL

String url = "jdbc:oracle:thin:@127.0.0.1:1521:DB_NAME";

C.建立连接

String username= "zhouchuandong";

String password = "xiaodong728";

Connection conn = DriverManager.getConnection(url,username,password);

D.创建Statement对象

Statement stmt = conn.createStatement();

 E.执行查询或更新SQL

String sql = "insert into student1 (id , name,sex ) values (1002,'黄国国','男')";

stmt.addBatch(sql);

F.结果处理

int[] count =stmt.executeBatch();
if(count.length>0){
System.out.println("加入成功!");
}

  G.关闭连接

conn.rollback();
stmt.close();

conn.close();

程序DEMO:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {
public static void main(String[] args) throws SQLException {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:DB_NAME";
String username= "zhouchuandong";
String password = "xiaodong728";
Statement stmt=null;
Connection conn=null;
try{
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
String sql = "insert into student1 (id , name,sex ) values (1002,'黄国国','男')";
String sql1 = "insert into student1(id , name,sex ) values (1003,'证券','男')";
String sql2 = "insert into student1 (id , name,sex ) values (1004,'郑轩','男')";
String sql3 = "insert into student1 (id , name,sex ) values (1005,'王伟','男')";
stmt.addBatch(sql);
stmt.addBatch(sql1);
stmt.addBatch(sql2);
stmt.addBatch(sql3);
int[] count =stmt.executeBatch();
if(count.length>0){
System.out.println("加入成功!");
}
conn.rollback();
stmt.close();
conn.close();
}catch(Exception e){
System.out.println("加载驱动失败"+e.getMessage());
}
}
}

你可能感兴趣的