Java connection mysql database messy code solution

  • 2020-04-01 01:57:31
  • OfStack

Solution 1:

Mysql installation code,

Take a look at my. Ini

 
[mysql] 

default-character-set=utf8 

[client] 
default-character-set=utf8 

[mysqld] 
default-character-set=utf8 Set when creating the table:  

DROP TABLE IF EXISTS `Company`; 
CREATE TABLE IF NOT EXISTS `Company` 
( 
`Cname` VARCHAR(10) NOT NULL, 
`Caddr` VARCHAR(100), 
`Ctel` VARCHAR(16) 
)ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

JSP header:

< % @page language=" Java "import="java.util.*" pageEncoding=" utf-8 "%> If not, try:

ContentType = "text/HTML. Charset = gb2312"

Solution 2:

When connecting to mysql (whether in the case of reading or fetching data from mysql), specify the encoding to be used as utf-8, as shown below

// load mysql-jdbc driver

Class.forname (". Com. Mysql. JDBC Driver "). The newInstance ();

// connect to database

The Connection sqlCon = DriverManager. GetConnection (" JDBC: mysql: / / localhost: 3306 / test? User = root&password = 1 & useUnicode = true&characterEncoding = utf-8 ");

Solution 3:

If method 1 does not work then cast the read string on the basis of method 1.

String name = request. The getParameter (" name ");
Name = new String (the name getBytes (" ISO - 8859-1 "), "utf-8");
Or:

String name =new String(rst.getString("name"). GetBytes (" iso-8859-1 "),"utf-8");

Solution 4:

This method is recommended in some articles, and I tried it first, but it didn't work. Here or say, I do not know whether I am operating error. Post the original first:

"If there is Chinese in the database and the default language of mysql is not Chinese, add a line in [mysqld] in the configuration file C:winntmy.ini:

Default - character - set = utf-8

Then restart mysql

Method 5: change in web.xml under a tomca or web project:

 
<filter> 
<filter-name>UTFEncoding</filter-name> 
<filter-class>com.founder.chenph.Util.EncodingFilter_UTF8 

</filter-class> 
<init-param> 
<param-name>encoding</param-name> 
<param-value>UTF-8</param-value> 
</init-param> 
</filter> 
<filter-mapping> 
<filter-name>UTFEncoding</filter-name> 
<url-pattern>*.jsp</url-pattern> 
</filter-mapping> 
<filter-mapping> 
<filter-name>UTFEncoding</filter-name> 
<url-pattern>*.do</url-pattern> 
</filter-mapping> 

Related articles: