我的项目旨在获取网址,获取所述网址的创建日期,并从网址中提取特定信息。当且仅当它们是英语和西班牙语时,所有这些参数都成功传递给mySQL;但是,每当我遇到一个外国摘录时,例如:
بسماللهالرحمنالرحيمنسألكمالدعاء
mysql将其翻译为:
??? ???? ?????? ?????? ?????? ??????
我知道这是一个UTF-8问题。在intellij上,当我打印这行时,我可以看到外国字符就好了,所以我假设无论JSoup检索到什么都没问题。
以下是Java代码。如果它很重要,我将使用c3p0连接到数据库。我相信建立与数据库的连接不是问题,但为了满足需要,我可以提供它。
import org.jsoup.Jsoup;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.PreparedStatement;
import org.jsoup.nodes.Document;
import java.beans.PropertyVetoException;
import com.mchange.v2.c3p0.*;
public class Connect {
private static final String URL = "jdbc:mysql://localhost:3306/testdb?allowMultiQueries=true";
private static final String USER = "root";
private static final String PASSWORD = "1234";
//Connection information here
public static void addlink(String url, String body, String createDate, String retrieveDate) { // adds html information to the database
Connection connection = null;
PreparedStatement statement = null;
try {
connection = cpds.getConnection();
statement = connection.prepareStatement("INSERT IGNORE INTO testtable(URL, Creation_Date, Retrieval_Date, Body) VALUES(?, ?, ?, ?);");
statement.setString(1, url);
statement.setString(2, createDate);
statement.setString(3, retrieveDate);
statement.setString(4, body);
statement.executeUpdate();
} catch // error handling
}
public void getPageData(String url, String retrieveDate) throws IOException { // gets the html information
Document doc = Jsoup.connect(url).userAgent("Mozilla").get();
String str = doc.body().text();
int endOfBody = str.length(); //for cutting out needless info in html text
StringBuilder body = new StringBuilder(str);
body.replace(0, 25, ""); // cut out unnecessary header info
body.replace(endOfBody - 128, endOfBody, ""); // cut out unnecessary trailer info
String finalBody = body.toString();
String createDate = finalBody.substring(finalBody.length()-10, finalBody.length());
addlink(url, finalBody, createDate, retrieveDate);
}
}
就我对数据库所做的更改而言,Url的主体作为MEDIUMTEXT传递,我做了:
mysql> ALTER TABLE testtable
-> DEFAULT CHARACTER SET utf8
-> collate utf8_general_ci
-> ;
提前感谢您提供的所有见解。
编辑:这已被标记为重复,但有问题的论坛帖子只是将mysql转换为unicode的一步。
答案 0 :(得分:1)
证明需要在Java代码中大量指定UTF-8才能使其工作。这是大纲:
1)将以下内容附加到用于连接mysql的URL(信用转到@Enwired):
useUnicode=yes&characterEncoding=UTF-8"
所以你得到:
URL = "jdbc:mysql://localhost:3306/testdb?useUnicode=yes&characterEncoding=UTF-8";
2)添加条目时,请在代码中添加以下内容:
java.sql.Statement unicode = null;
try {
// note, how you connect does not matter
connection = cpds.getConnection();
unicode = connection.createStatement();
unicode.executeQuery("SET NAMES 'UTF8';");
unicode.executeQuery("SET CHARACTER SET 'UTF8';");
// Other prepared statements.
} catch (SQLException e) {
// ...
3)进入mysql并更改将接收utf8字符的数据库,表和列的排序规则。 How to change the default collation of a database?
您的mysql服务器现在应该接受unicode。