1.导包
2.加载驱动
class.forName("com.mysql.jdbc.Driver")
3.创建连接
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","a")
数据库所在的IP地址:数据库所占用的端口号:要连接的数据库名
4.创建执行语句块
•要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3
种类型:
1、执行静态SQL语句。通常通过Statement实例实现。
2、执行动态SQL语句。通常通过PreparedStatement实例实现。
3、执行数据库存储过程。通常通过CallableStatement实例实现。
具体的实现方式:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt =
con.prepareCall("{CALL demoSp(? , ?)}") ;
5.执行并获取结果
Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate
和execute
1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句
,返回一个结果集(ResultSet)对象。
2、int executeUpdate(String sqlString):用于执行INSERT、UPDATE或
DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等
3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的
语句。
具体实现的代码:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
int rows = stmt.executeUpdate("INSERT INTO ...") ;
6.关闭连接
JDBC是一套规范
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestOracl {
public static void main(String[] args) {
Connection con=null; //创建一个数据库连接
Statement stmt =null;//创建预编译语句对象,一般是用这个
ResultSet rs=null; //创建一个结果集对象
//加载驱动
try {
//实例化oracle数据库驱动程序(建立中间件)
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("开始连接数据库。。。");
//@localhost为服务器名,scott为用户 a为密码
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","a");
//提交sql语句,创建一个Statement对象来将SQL语句发送到数据库
stmt=con.createStatement();
String sql="select * from dept";
//查询数据用executeQuery
rs = stmt.executeQuery(sql);//执行查询,(dept)为表名
while (rs.next()) {//使当前记录指针定位到记录集的第一条记录
System.out.println( rs.getInt("deptno")+"\t"+rs.getString("dname")+"\t"+rs.getString("loc"));
}//1代表当前记录的第一个字段的值,可以写成字段名。
//2代表当前记录的第二个字段的值,可以写成字段名。
//添加数据用executeUpdate
//stmt.executeUpdate("insert into dept values(7,'张学友')");
//修改数据用executeUpdate
//stmt.executeUpdate("update dept set dname = '张学友' where deptno = 7");
//删除 数据用executeUpdate
//stmt.executeUpdate("delete from dept where deptno = 60");
// if(result>0){
// System.out.println("删除成功...");
// }else{
// System.out.println("删除失败...");
// }
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
//关闭数据库,结束进程
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}