共計 1374 個字符,預計需要花費 4 分鐘才能閱讀完成。
可以使用 Java 的 JDBC 庫來連接到 SQL數據庫 ,并執行相應的 SQL 語句來上傳文本文件。
以下是一個示例代碼:java
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class FileUploadToSQL {
public static void main(String[] args) {
// 連接到 SQL 數據庫
String url = "jdbc:mysql://localhost:3306/databaseName";
String username = "username";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, username, password)) {
// 讀取文本文件內容
String filePath = "pathToFile.txt";
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
// 插入文本內容到 SQL 數據庫
String sql = "INSERT INTO tableName (column) VALUES (?)";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, stringBuilder.toString());
statement.executeUpdate();
System.out.println(" 文件上傳成功!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
其中,jdbc:mysql://localhost:3306/databaseName
是數據庫的連接 URL,username
和 password
分別是數據庫的用戶名和密碼。pathToFile.txt
是要上傳的文本文件的路徑,tableName
是要上傳到的數據庫表名,column
是表中存儲文本內容的列名。
請根據實際情況修改這些值,并借助適當的 JDBC 驅動。
丸趣 TV 網 – 提供最優質的資源集合!