jdbc

  2. JDBC API :主要功能:

                三件事:具体是通过一下类/接口实现:

                                    DriverManager:管理jdbc驱动

                                         Connection:连接

         Statement(PreparedStatement):增删改查

                              CallableStatement:调用数据库中的 存储过程/存储函数

                                                 Result:返回的结果集

         总结:

                 Statement(PreparedStatement):增删改查(通过Connection产生)

                                       CallableStatement:调用数据库中的存储过程/存储函数(通过Connection产生)

 

                      Result:返回的结果集(上面的Statement等产生)

 

          Connection产生操作数据库的对象:

                       Connection产生Statement对象:createStatement()

      Connection产生PreparedeStatement对象:prepareStatement()

          Connection产生CallableStatement对象:prepareCall()

 

            Statement操作数据库:

                                   增删改:executeUpdate()

                                       查询:executeQuery;

 

                   ResultSet:保存结果集 select * from xxx

                             next() :  光标下移,判断是否有下一条数据:true/false

                       previous():true/false (往上)

   getXxx(字段名 or 位置):获取具体的字段值

 

           RreparedStatement操作数据库:

                     public interface PreparedStatement extends Statement

                               因此

                                      增删改:executUpdate()

                                          查询:executeQuery()

                                   赋值操作: setXxx();

 

                3. jdbc访问数据库的具体步骤:

                                    ①导入驱动,加载具体的驱动类

                                    ②与数据库建立链接

                                    ③发送sql,执行 ​ ④处理结果集(查询)

 

 

package JdebcDemo01;

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

import com.mysql.cj.Query;

public class JDBCDemo
{
private static final String URL="jdbc:mysql://localhost:3306/adds";
private static final String username="root";
private static final String password="123456";
static Connection connection=null;
static Statement createStatement=null;
static ResultSet resultSet;

public static void update() {//增删改

try {
//①导入
Class.forName("com.mysql.jdbc.Driver");

//②与数据库建立连接,首先通过DriverManager建立连接
   connection = DriverManager.getConnection(URL, username, password);//ctrl+1返回值
   
//③发送sql, 执行(①增删改,②查(两大类))
createStatement = connection.createStatement();
//String sql="insert into student values(1,'zs',33,'mz')";//增(插入)
// String sql="update student set name='ls' where id=1";//修改
String sql="delete from student where id=1"; //删除

//执行SQL(增删改executeUpdate(),查询executeQuery())
int count=createStatement.executeUpdate(sql);

//处理结果
if (count>0) {
System.out.println("操作成功");
}


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

try {
if(createStatement!=null)createStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

    //查询
public static void query() {
try {

Class.forName("com.mysql.jdbc.Driver");

//②与数据库建立连接,首先通过DriverManager建立连接
   connection = DriverManager.getConnection(URL, username, password);//ctrl+1返回值
   
//③发送sql, 执行(①增删改,②查(两大类))
createStatement = connection.createStatement();
String sql="select id,name from zjw";

//查询executeQuery()
 resultSet=createStatement.executeQuery(sql);
 
//处理结果
while(resultSet.next())
{
int sno=resultSet.getInt("id");
String sname= resultSet.getString("name");
System.out.println(sno+"--"+sname);
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {

if(resultSet!=null)resultSet.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if(createStatement!=null)createStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
  }

public static void main(String[] args) {
//update();
     query();
}
}

   推荐使用PreparedStatement:原因如下:
     1.编码更加简便 (避免了字符串的拼接)
         String name="zs"
          int age=23;
         ①Statement :
             String sql="insert into studet(stuno,stuname) values('+name+','+age+')";

     PreparedStatement :
          String sql="insert into student(stuno,stuname) values(?,?)";
               pstmt= connection.preareStatement(sql);//预编译SQL
                 pstmt.setString(1,name);
             pstmt.setInt(2,age);

       2.提高性能 (因为有预编译操作,预编译只需要执行一次)
         例:需要重复增加100条
    ①Statement:
        String sql="insert into studet(stuno,stuname) values('+name+','+age+')";
          for(100)
              stmt.executeUpdate(sql);

  ②PreparedStatement:
        String sql="insert into student(stuno,stuname) values(?,?)";
          pstmt= connection.preareStatement(sql);//预编译SQL
          pstmt.setString(1,name);
          pstmt.setInt(2,age);
        for(100){
              pstmt.executeUpdage();

     3.安全(可以有效防止sql注入)
sql注入:将客户端输入的内容 和 开发人员的SQL语句 混为一体

 

   jdbc异常总结:

            加载驱动的:ClassNotFoundException(可能类不存在)

                其它类等:SQLException

                   finally: 一定要保持不为空:!=null 打开顺序,与关闭顺序相反 先打开的后关闭,后打开的先关闭

              jdbc中,除了Class.forName()抛出ClassNotFoundException,其余方法全部抛SQLException

 

         CallableStatement:调用存储过程,存储函数

                 connection.prepareCall(参数:存储过程or存储函数)

              参数格式:

                  存储过程(无返回值return,用Out参数替代):

                                {call 存储过程名(参数列表)} 存储函数(有返回值return):

                                {?=call 存储函数名(参数列表)}

 

             强调:

                      如果通过sqlplus访问数据库,只需要开启:OracleServiceSID

                   通过其他程序访问数据(sqldevelop,Navicat,JDBC),需要开启:OracleServiceSID,XxxListener

 

                JDBC调用存储过程的步骤: CREATE OR REPLACE PROCEDURE addTwoNum(num1 in number,num2 in number,result out number) -- 1+2->3

                                 ①.产生调用存储过程的对象: preparecall = connection.prepareCall("{call addTwoNum(?,?,?)}");

                                 ②.通过setXxx()处理输出参数值 preparecall.setInt(1, 10);

                                 ③通过 registerOutParameter(...) 处理输出参数类型

                                 ④ preparecall.execute() 执行

                                 ⑤ 接收 输出值(返回值)getXxx()

package JdebcDemo01;

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

import com.mysql.cj.jdbc.CallableStatement;

public class JDBCCallableStatement
{
private static final String URL="jdbc:mysql://localhost:3306/adds";
private static final String username="root";
private static final String password="123456";
static Connection connection=null;
static java.sql.CallableStatement callableStatement=null;

public static void invokeProcedure() {

try {
//①导入
Class.forName("com.mysql.jdbc.Driver");

//②与数据库建立连接,首先通过DriverManager建立连接
   connection = DriverManager.getConnection(URL, username, password);//ctrl+1返回值
   
//③发送sql, 执行(①增删改,②查(两大类)) num1+num2->num3

   callableStatement=connection.prepareCall("{call addTwoNum(?,?,?)}");
callableStatement.setInt(1, 10);
callableStatement.setInt(2, 10);
//设置输出参数类型
callableStatement.registerOutParameter(3, Types.INTEGER);
callableStatement.execute();//num1+num2,execute()之前处理输入参数以及输出参数类型,之后接收输出参数值

int result=callableStatement.getInt(3);//获取计算结果
System.out.println(result);
//处理结果
if (result>0) {
System.out.println("操作成功");
}


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

try {
if(callableStatement!=null)callableStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

          调用存储函数:

                  数据库语法:

                         CREATE OR REPLACE FUNCTION addTwoNumfunction(num1 in number,num2 in number) -- 1+2

                             return number

                            as

                          result nuber;

                         begin

                 result:=num1+num2;

                    return result;

                          end;

                     /

public static void invokeFunction() {

try {
//①导入
Class.forName("com.mysql.jdbc.Driver");

//②与数据库建立连接,首先通过DriverManager建立连接
   connection = DriverManager.getConnection(URL, username, password);//ctrl+1返回值
   
//③发送sql, 执行(①增删改,②查(两大类)) num1+num2->num3

   callableStatement=connection.prepareCall("{?=call addTwoNumfunction(?,?)}");
callableStatement.setInt(2, 10);
callableStatement.setInt(3, 10);
//设置输出参数类型
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.execute();//num1+num2,execute()之前处理输入参数以及输出参数类型,之后接收输出参数值

int result=callableStatement.getInt(1);//获取计算结果
System.out.println(result);
//处理结果
if (result>0) {
System.out.println("操作成功");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(callableStatement!=null)callableStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

   JDBCD调用存储函数:

              与调存储过程的区别: 在调用时,注意参数

 

            处理CLOB(Text)/BLOB类型

                    CLOB:大文本数据(小说->数据)

                     BLOB:二进制

     CLOB :

1.先通过...? 代替小说内容(占位符)
2.再通过createStatement.setCharacterStream(2,reader,(int)file.length());将上一步的 ? 替换为小说流,注意第三个参数是int类型
package JdebcDemo01;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCClob
{
static String url="jdbc:oracle:thin:@localhost:1521:ORCL";
static String user="root";
static String password="123456";
  static Connection connection;
   static  PreparedStatement createStatement;
   //通过jdbc存储大文本数据(小说)CLOB
   //设置CLOB类型:setCharacterStream
public static void ClobDemo() throws ClassNotFoundException, SQLException, FileNotFoundException, UnsupportedEncodingException
{
 Class.forName("com.mysql.jdbc.Driver");
  connection = DriverManager.getConnection(url, user, password);
  String sql="insert into mynovol values(?,?)";
createStatement= connection.prepareStatement(sql);
createStatement.setInt(1, 1);
File file=new File("D:all.txt");//小说
InputStream inputStream=new FileInputStream(file);
Reader reader=new InputStreamReader(inputStream,"UTF-8" );//转换流可以设置编码
createStatement.setCharacterStream(2, reader,(int)file.length());//通过流把小说写进去//第三个位置是小说的长度
int count= createStatement.executeUpdate();
 if (count>0)
{
System.out.println("操作成功");
}
 connection.close();
 createStatement.close();
}

   取:

 

 

 

posted @ 2022-10-05 15:54  zjw_rp  阅读(2)  评论(0编辑  收藏  举报