2.获取连接 Connection conn=DriverManager.getConnection(URL,USER,PASSWORD);
3.编写SQL语句并发送 PrepapredStatement pstm=conn.prepareStatement(sql);
4.获得数据库返回结果 (ResultSet rs) 增删改(int)
5.关闭资源 public static void closeResource(Connection conn,PreparedStatement pstm,ResultSet rs)
接下来我们开始编写JDBC程序代码,实现CLOB类型数据的读写操作,在完成此任务之前,
先将JDBC连接数据库以及关闭数据库代码编写一个MySQLConnectionUtil.java类中,该类的代码如下所示:
package com.guigu.jdbc; import java.sql.*; public class MySQLConnectionUtil { private static String DRIVER="com.mysql.jdbc.Driver"; private static String URL="jdbc:mysql://127.0.0.1:3306/lob"; private static String USERNAME="root"; private static String PASSWORD="123456"; public static Connection getConnection(){ Connection connection=null; try { Class.forName(DRIVER); connection= DriverManager.getConnection(URL,USERNAME,PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){ try { if(resultSet!=null){ resultSet.close(); } if (preparedStatement!=null){ preparedStatement.close(); } if (connection!=null){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
package com.guigu.jdbc; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class JDBCMySQLCOLBWriter { public static void main(String[] args) { String sql="INSERT INTO TEXTCLOB VALUES (?,?,?)"; Connection connection=MySQLConnectionUtil.getConnection(); PreparedStatement preparedStatement=null; try { preparedStatement=connection.prepareStatement(sql); File file =new File("D:/workspace/site.txt"); //使用输入流读写文本文件 InputStream inputStream=new FileInputStream(file); //加载SQL语句中VALUES占位符参数 preparedStatement.setInt(1,1); preparedStatement.setString(2,"site.txt"); preparedStatement.setAsciiStream(3,inputStream); int count = preparedStatement.executeUpdate(); if(count>0){ System.out.println("数据插入成功"); }else{ System.out.println("数据插入失败"); } } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); }finally { MySQLConnectionUtil.close(connection,preparedStatement,null); } } }