如何使用 jsp 在数据库中获取希腊字符
我正在尝试使用 jsp 程序在数据库中插入一些希腊名字。然而,数据库中的结果只是“???”而不是希腊字符。如果我尝试使用 phpmyadmin 或命令行插入希腊名称,那么就没有问题。所以我猜我的jsp代码有问题。这是我的代码的一个简单部分:
尝试
{
Statement stmt;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/test?useEncoding=true&characterEncoding=UTF-8&autoReconnect=true";
Connection con =(Connection) DriverManager.getConnection(url,"root", "");
con.setCharacterEncoding("utf-8");
stmt = (Statement) con.createStatement();
stmt.executeQuery("SET NAMES 'UTF8'");
stmt.executeQuery("SET CHARACTER SET 'UTF8'");
String greekname = "κωνσταντίνα";
stmt.executeUpdate("INSERT INTO users(name,age) VALUES ('" + greekname + "','" + "44" +"')");
con.close();
}catch( Exception e ) {System.out.println("Problem during the connection with the database!");}
我希望有人对此有一个好主意!
i'm trying to insert some greek names in a database using a jsp programme. However, the result in the database is simply "????" instead of greek characters. If I try to insert a greek name using phpmyadmin or the command line, then there is no problem. So I guess there is some trouble in my jsp code. Here is a simple part of my code:
try
{
Statement stmt;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/test?useEncoding=true&characterEncoding=UTF-8&autoReconnect=true";
Connection con =(Connection) DriverManager.getConnection(url,"root", "");
con.setCharacterEncoding("utf-8");
stmt = (Statement) con.createStatement();
stmt.executeQuery("SET NAMES 'UTF8'");
stmt.executeQuery("SET CHARACTER SET 'UTF8'");
String greekname = "κωνσταντίνα";
stmt.executeUpdate("INSERT INTO users(name,age) VALUES ('" + greekname + "','" + "44" +"')");
con.close();
}catch( Exception e ) {System.out.println("Problem during the connection with the database!");}
I hope someone has a good idea about it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当数据库表检索到未被指示数据库表存储字符的字符编码所覆盖的字符时,数据库表将执行此操作。您需要确保按如下方式创建数据库和表:
另请参阅:
与具体问题无关,在每个查询上加载驱动程序是不必要的。只需在应用程序启动期间一次就足够了。另外,资源的关闭应该发生在
finally
块中,否则在出现异常的情况下您将面临资源泄漏的风险。最后,在 JSP 文件中编写原始 Java 代码也不是最佳实践;)The database table will do that when it retrieves characters which are not covered by the character encoding which the database table is been instructed to store the characters with. You need to ensure that the database and table is created as follows:
See also:
Unrelated to the concrete problem, loading the driver on every query is unnecessary. Just only once during application's startup is enough. Also, closing of resources should happen in
finally
block, else you risk resource leaks in case of exceptions. Finally, writing raw Java code in a JSP file is not the best practice as well ;)第一个答案中的链接为我解决了问题。这是连接字符串
数据库。我只使用了
但添加其余的解决了问题。
谢谢。
拍
The link in the first answer solved the problem for me. It was the connect string to
the database. I was using just
but adding the rest solved the problem.
Thanks.
Pat