Java使用MySQL數據庫連接
Java連接MySQL數據庫是非常常見的。下面是一個簡單的Java代碼片段,用于連接到MySQL數據庫。在這個代碼段中,我們使用了JDBC驅動程序,它是MySQL數據庫的默認驅動程序。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLJDBCUtil {
private static String jdbcURL = "jdbc:mysql://localhost:3306/sampleDB";
private static String jdbcUsername = "root";
private static String jdbcPassword = "root";
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
}
MySQL使用PDF進行文檔管理
MySQL數據庫支持將PDF文檔存儲在BLOB(Binary Large Object)列中。這種做法對于需要管理大量PDF文檔的應用程序非常有用。下面是一個簡單示例,可用于將PDF文件插入到MySQL數據庫中:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PDFFileInsertion {
private static final String INSERT_PDF_FILE_SQL = "INSERT INTO pdf_files(file_name, file_data) VALUES (?, ?)";
public void insertPDFFile(String fileName, File pdfFile) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/pdfDB", "root", "root");
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_PDF_FILE_SQL)) {
preparedStatement.setString(1, fileName);
preparedStatement.setBinaryStream(2, new FileInputStream(pdfFile));
preparedStatement.executeUpdate();
} catch (SQLException | FileNotFoundException e) {
e.printStackTrace();
}
}
}
將PDF文件存儲到百度云中
百度云提供了一組API,用于將文件(包括PDF文件)上傳到百度云中。上傳文件使用的API是BosClient.putObject()。
import com.baidubce.auth.BceCredentials;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.model.PutObjectResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class PDFUploadToBaiduCloud {
private static final String ACCESS_KEY_ID = "XXXXXXXXXXXXXXXXXXXXXXX";
private static final String SECRET_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXXXXX";
private static final String ENDPOINT = "http://bj.bcebos.com";
public void uploadPDFToBaiduCloud(String fileName, File pdfFile) {
String bucketName = "my-bucket";
String objectKey = fileName;
BceCredentials credentials = new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
BosClient bosClient = new BosClient(credentials, ENDPOINT);
InputStream inputStream = null;
PutObjectResponse putObjectResponse = null;
try {
inputStream = new FileInputStream(pdfFile);
putObjectResponse = bosClient.putObject(bucketName, objectKey, inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
上一篇mysql 50710
下一篇mysql 57安裝