JDBC

jdbc是java连接数据库的方法,对于不同的数据库,我们需要引入不同的jar包。

数据库具体驱动类驱动jar连接字符串
oracleoracle.jdbc.OracleDriverojdbc-x.jarjdbc:oracle:thin:@localhost:1521:ORCL
mysqlcom.mysql.jdbc.Driversql-connector-java-x.jarjdbc:mysql://localhost:3306/数据库实例名
sqlservercom.microsoft.sqlserver.jdbc.SQLServerDriversqljdbc-x.jarjdbc:microsoft:sqlserver:localhost:1433:databasename数据库实例名

本文拿oracle举例子。首先需要下载oracle数据库,其内部自带ojdbc14.jar,直接把他复制导入项目中。
1.现在数据库中创建一张表

create table mytab (id number,name varchar2(10));
insert into mytab values(5,'sssxll');
insert into mytab vlues(7,'wqasxd');

创建一个java类,举例子

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo {
    private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL" ;
    private static final String USERNAME = "scott" ;
    private static final String PWD = "tiger" ;
    
 public static void update() {//增删改
  Statement stmt =null;
  Connection connection = null;
  try {
//  a.导入驱动,加载具体的驱动类
  Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//  b.与数据库建立连接
     connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
//  c.发送sql,执行(增删改)
     stmt = connection.createStatement() ;
     //增加为下面的语句:
  String sql = "insert into mytab values(1,'ls')";
 //执行SQL
  int count = stmt.executeUpdate(sql);//返回值表示增删改  几条数据
  //d.处理结果
  if(count>0) {
   System.out.println("操作成功!");
  }
  }catch(ClassNotFoundException e) {
   e.printStackTrace();
   
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
              if(stmt!=null)stmt.close();
              if(connection!=null)connection.close();
   }catch(SQLException e) {
                    e.printStackTrace();    
   }
  }
  
 }
 //查找
 public static void query() {
  Statement stmt =null;
  Connection connection = null;
  ResultSet rs = null;
  try {
//  a.导入驱动,加载具体的驱动类
  Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//  b.与数据库建立连接
     connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
//  c.发送sql,执行查
     stmt = connection.createStatement() ;
     //模糊查询名字有x 的信息
     String name = "x";
     String sql="select *from mytab where name like '%"+name+"%'";
  //执行SQL(增删改是executeUpdate(),查询executeQuery())
  rs = stmt.executeQuery(sql);//默认指向第0行  next():1:下移,2判断下移之后的元素是否为空   如果有数据true 为空false
                              //rs.getXxx();  获取rs指向行的数据  eg:getInt() getString() getDate()
  //d.处理结果
     while(rs.next()) {
      //下面的两行语句可以用 序列号替代
      /*int sno = rs.getInt("id");
      String sname = rs.getString("name");*/  //开发推荐写第一个   因为下面的比较乱 
      int sno = rs.getInt(1);//下标:从1开始计数
      String sname = rs.getString(2);
      System.out.println(sno+"----"+sname);
     }
  }catch(ClassNotFoundException e) {
   e.printStackTrace();
   
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
        if(rs!=null)rs.close();
              if(stmt!=null)stmt.close();
              if(connection!=null)connection.close();//顺序;先打开的 后关  就像堆栈一样
   }catch(SQLException e) {
                    e.printStackTrace();    
   }
  }
  
 }
 public static void main(String[] args) {
  update();
  //query();
 }
}

上面是用普通的Statement操作的,虽然具有操作性,但是statement有SQL注入的风险,推荐用他的子类PreparedStatement.其实用法大同小异,下面是其用法的案例:

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCPreparedStatementDemo {
    private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL" ;
    private static final String USERNAME = "scott" ;
    private static final String PWD = "tiger" ;
    
 public static void update() {//增删改
  Connection connection =null;
  PreparedStatement pstmt = null;
  try {
//  a.导入驱动,加载具体的驱动类
  Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//  b.与数据库建立连接
     connection = DriverManager.getConnection(URL,USERNAME,PWD) ;

//就是下面不一样!!!!!!!!
//!!!!!!!!!!
//!!!!!!!!!!
String sql = "insert into mytab values(?,?)";//可以用?充当占位符
     pstmt = connection.prepareStatement(sql);//预编译
     pstmt.setInt(1,36);//1表示替代第一问号  为36
     pstmt.setString(2,"lzl");
     int count = pstmt.executeUpdate();
//d.处理结果
  if(count>0) {
   System.out.println("操作成功!");
  }
  }catch(ClassNotFoundException e) {
   e.printStackTrace();
   
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
              if(pstmt!=null)pstmt.close();
              if(connection!=null)connection.close();
   }catch(SQLException e) {
                    e.printStackTrace();    
   }
  }
  
 }
//查找
 public static void query() {
  PreparedStatement pstmt =null;
  Connection connection = null;
  ResultSet rs = null;
  try {
//  a.导入驱动,加载具体的驱动类
  Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//  b.与数据库建立连接
     connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
     
     
     
     String sql="select *from mytab where name like ?";
//  c.发送sql,执行查
     pstmt = connection.prepareStatement(sql) ;
     pstmt.setString(1,"%x%");
 
  rs = pstmt.executeQuery();
  //d.处理结果
     while(rs.next()) {
      //下面的两行语句可以用 序列号替代
      /*int sno = rs.getInt("id");
      String sname = rs.getString("sname");*/  //开发推荐写第一个   因为下面的比较乱 
      int sno = rs.getInt(1);//下标:从1开始计数
      String sname = rs.getString(2);
      System.out.println(sno+"----"+sname);
     }
  }catch(ClassNotFoundException e) {
   e.printStackTrace();
   
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
        if(rs!=null)rs.close();
              if(pstmt!=null)pstmt.close();
              if(connection!=null)connection.close();
   }catch(SQLException e) {
                    e.printStackTrace();    
   }
  }
  
 }
 public static void main(String[] args) {
//  update();
 query();
 }
}

很显然上面的连接字符要方便的多!
如果调用存储过程或者存储函数就要用到另一个子类CallableStatement:
首先得有存储过程和存储函数:

--创建存储过程
create or replace procedure addTwoNum(num1 in number,num2 in number,result out number) 
as
begin
result := num1  + num2 ;
end ;    
 /  
 --创建存储函数
create or replace function addTwoNumfunction(num1 in number,num2 in number) --1+2->3
return number
as
   result number;
begin
result := num1  + num2 ;
return result;
end ;
/

下面是例子:

import java.sql.Statement;
import java.sql.Types;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCCallableStatement2 {
    private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL" ;
    private static final String USERNAME = "scott" ;
    private static final String PWD = "tiger" ;
    //调用存储函数
 public static void invokeFunction() {
  CallableStatement cstmt =null;
  Connection connection = null;
  try {
//  a.导入驱动,加载具体的驱动类
  Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//  b.与数据库建立连接
     connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
//c.发送sql,执行(增删改)
     cstmt = connection.prepareCall("{? = call addTwoNumfunction(?,?)}");//调用addTwoNum存储函数
     cstmt.setInt(2,52);
     cstmt.setInt(3,10);
     //上面是 输入参数  下面是输出参数
        cstmt.registerOutParameter(1,Types.INTEGER);
  cstmt.execute();//num1+num2
  //设置输出参数的类型
  int result = cstmt.getInt(1);
  System.out.println(result);
       }catch(ClassNotFoundException e) {
   e.printStackTrace();
   
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
              if(cstmt!=null)cstmt.close();
              if(connection!=null)connection.close();
   }catch(SQLException e) {
                    e.printStackTrace();    
   }
  }

 }

//调用存储过程
 public static void invokeProcedure() {
  CallableStatement cstmt =null;
  Connection connection = null;
  try {
//  a.导入驱动,加载具体的驱动类
  Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//  b.与数据库建立连接
     connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
     
     
     
  //c.发送sql,执行(增删改)
     cstmt = connection.prepareCall("{call addTwoNum(?,?,?)}");//调用addTwoNum存储过程
     cstmt.setInt(1,16);
     cstmt.setInt(2,10);
     //上面是 输入参数  下面是输出参数
  cstmt.registerOutParameter(3,Types.INTEGER);
  cstmt.execute();//num1+num2
  //设置输出参数的类型
  int result = cstmt.getInt(3);
  System.out.println(result);
 }catch(ClassNotFoundException e) {
   e.printStackTrace();
   
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }finally {
   try {
              if(cstmt!=null)cstmt.close();
              if(connection!=null)connection.close();
   }catch(SQLException e) {
                    e.printStackTrace();    
   }
  }
  
 }

 public static void main(String[] args) {
 //invokeProcedure();
invokeFunction();
 }
}
     

当然数据库也可以存储大文本数据,具体用到Clob和BLob这两个属性。
Clob(可以存放小说这些普通的数据)

create table mynovel(id number primary key,novel clob);
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCClob {
     private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL" ;
      private static final String USERNAME = "scott" ;
      private static final String PWD = "tiger" ;
      //通过jdbc存储大文本数据(小说)
      //设置CLOB类型:setCharacterStream
   public static void clobDemo() {
    PreparedStatement pstmt =null;
    Connection connection = null;
    try {
//    a.导入驱动,加载具体的驱动类
    Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//    b.与数据库建立连接
       connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
      
//    c.发送sql,执行(增删改)
       String sql = "insert into mynovel values(?,?)";
       pstmt = connection.prepareStatement(sql) ;
       //增加为下面的语句:
    pstmt.setInt(1,1);
    File file=new File("G:\\all.txt");
    InputStream in = new FileInputStream(file);
    Reader reader = new InputStreamReader(   in ,"UTF-8");
    pstmt.setCharacterStream(2,reader,(int)file.length());
    
    int count = pstmt.executeUpdate();
    //d.处理结果
    if(count>0) {
     System.out.println("操作成功!");
    }
    reader.close();
    }catch(ClassNotFoundException e) {
     e.printStackTrace();
     
    }catch(SQLException e){
     e.printStackTrace();
    }catch(Exception e){
     e.printStackTrace();
    }finally {
     try {
                if(pstmt!=null)pstmt.close();
                if(connection!=null)connection.close();
     }catch(SQLException e) {
                      e.printStackTrace();    
     }
    }
    
   }
   //读取小说
   public static void clobReaderDemo() {
    PreparedStatement pstmt =null;
    Connection connection = null;
    ResultSet rs=null;
    try {
//    a.导入驱动,加载具体的驱动类
    Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//    b.与数据库建立连接
       connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
      
//    c.发送sql,执行(增删改)
       String sql = "select NOVEL from mynovel where id =?";
       pstmt = connection.prepareStatement(sql) ;
       //增加为下面的语句:
    pstmt.setInt(1,1);
    rs = pstmt.executeQuery();
    if(rs.next()) {
     Reader reader = rs.getCharacterStream("NOVEL");
     //io
     Writer writer = new FileWriter("src/小说.txt");
     char[] chs = new char[100];
     int len=-1;
     while((len=reader.read(chs))!=-1) {
      writer.write(chs,0,len);
     }
     writer.close();
     reader.close();
    }
}catch(ClassNotFoundException e) {
     e.printStackTrace();
     
    }catch(SQLException e){
     e.printStackTrace();
    }catch(Exception e){
     e.printStackTrace();
    }finally {
     try {
                if(pstmt!=null)pstmt.close();
                if(connection!=null)connection.close();
     }catch(SQLException e) {
                      e.printStackTrace();    
     }
    }
    
   }
   public static void main(String[] args) {
    //clobDemo();
    clobReaderDemo();
   }
 }

Blob(可以存放任何文件)

create table mymusic(id number primary key,music Blob);
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCBlob {
     private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL" ;
      private static final String USERNAME = "scott" ;
      private static final String PWD = "tiger" ;
      //通过jdbc存储大文本数据(mp3)
      //设置BLOB类型:setBinaryStream
   public static void blobDemo() {
    PreparedStatement pstmt =null;
    Connection connection = null;
    try {
//    a.导入驱动,加载具体的驱动类
    Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//    b.与数据库建立连接
       connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
      
//    c.发送sql,执行(增删改)
       String sql = "insert into mymusic values(?,?)";
       pstmt = connection.prepareStatement(sql) ;
       //增加为下面的语句:
    pstmt.setInt(1,1);
    File file=new File("G:\\lzl.mp3");
    InputStream in = new FileInputStream(file);
    pstmt.setBinaryStream(2,in,(int)file.length());
    
    int count = pstmt.executeUpdate();
    //d.处理结果
    if(count>0) {
     System.out.println("操作成功!");
    }
    in.close();
    }catch(ClassNotFoundException e) {
     e.printStackTrace();
     
    }catch(SQLException e){
     e.printStackTrace();
    }catch(Exception e){
     e.printStackTrace();
    }finally {
     try {
                if(pstmt!=null)pstmt.close();
                if(connection!=null)connection.close();
     }catch(SQLException e) {
                      e.printStackTrace();    
     }
    }
    
   }
   //读取二进制
   public static void blobReaderDemo() {
    PreparedStatement pstmt =null;
    Connection connection = null;
    ResultSet rs=null;
    try {
//    a.导入驱动,加载具体的驱动类
    Class.forName("oracle.jdbc.OracleDriver");//加载具体的驱动类
//    b.与数据库建立连接
       connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
      
//    c.发送sql,执行(增删改)
       String sql = "select music from mymusic where id =?";
       pstmt = connection.prepareStatement(sql) ;
       //增加为下面的语句:
    pstmt.setInt(1,1);
    rs = pstmt.executeQuery();
    if(rs.next()) {
     InputStream in = rs.getBinaryStream("music");
     //io
     OutputStream out = new FileOutputStream("src/music.mp3");
     byte[] chs = new byte[100];
     int len=-1;
     while((len=in.read(chs))!=-1) {
      out.write(chs,0,len);
     }
     out.close();
     in.close();
    }
    }catch(ClassNotFoundException e) {
     e.printStackTrace();
     
    }catch(SQLException e){
     e.printStackTrace();
    }catch(Exception e){
     e.printStackTrace();
    }finally {
     try {
                if(pstmt!=null)pstmt.close();
                if(connection!=null)connection.close();
     }catch(SQLException e) {
                      e.printStackTrace();    
     }
    }
    
   }
   public static void main(String[] args) {
    //blobDemo();
    blobReaderDemo();
   }
}

以上基本涵盖了jdbc的所有操作,如果有收获记得给博主点赞加关注哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

键盘歌唱家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值