1. 程式人生 > 實用技巧 >常用十大演算法(六)— 普里姆演算法

常用十大演算法(六)— 普里姆演算法

JDBC連線資料庫的主要步驟:

1. Class.forName("com.mysql.jdbc.Driver");//反射 類物件 四種

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類中,該類的程式碼如下所示:

1.工具類 方法:封裝,設定為靜態方法,好處,呼叫方便.

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);
        }
    }
}
上面的示例中,我們需要將文字檔案以檔案流的方式寫入MySQL資料庫指定的欄位是時,需要使用PreparedStatement物件呼叫其setAsciiStream()為儲存文字檔案載入資料.