最近准备学mysql 结果 出现中文乱码
在控制台查询的时候输出正常,
当我用jdbc链接到数据库的时候,用system.out.println()输出的时候就出现乱码
网上查了很多都解决不了,请高手帮忙!!!

解决方案 »

  1.   

    修改mysql安装目录下的my.ini文件
    招到两处字符集设置
    [code=INIFile]
    # MySQL Server Instance Configuration File
    # ----------------------------------------------------------------------
    # Generated by the MySQL Server Instance Configuration Wizard
    #
    #
    # Installation Instructions
    # ----------------------------------------------------------------------
    #
    # On Linux you can copy this file to /etc/my.cnf to set global options,
    # mysql-data-dir/my.cnf to set server-specific options
    # (@localstatedir@ for this installation) or to
    # ~/.my.cnf to set user-specific options.
    #
    # On Windows you should keep this file in the installation directory 
    # of your server (e.g. C:\Program Files\MySQL\MySQL Server 4.1). To
    # make sure the server reads the config file use the startup option 
    # "--defaults-file". 
    #
    # To run run the server from the command line, execute this in a 
    # command line shell, e.g.
    # mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 4.1\my.ini"
    #
    # To install the server as a Windows service manually, execute this in a 
    # command line shell, e.g.
    # mysqld --install MySQL41 --defaults-file="C:\Program Files\MySQL\MySQL Server 4.1\my.ini"
    #
    # And then execute this in a command line shell to start the server, e.g.
    # net start MySQL41
    #
    #
    # Guildlines for editing this file
    # ----------------------------------------------------------------------
    #
    # In this file, you can use all long options that the program supports.
    # If you want to know the options a program supports, start the program
    # with the "--help" option.
    #
    # More detailed information about the individual options can also be
    # found in the manual.
    #
    #
    # CLIENT SECTION
    # ----------------------------------------------------------------------
    #
    # The following options will be read by MySQL client applications.
    # Note that only client applications shipped by MySQL are guaranteed
    # to read this section. If you want your own MySQL client program to
    # honor these values, you need to specify it as an option during the
    # MySQL client library initialization.
    #
    [client]port=3306[mysql]default-character-set=gbk
    # SERVER SECTION
    # ----------------------------------------------------------------------
    #
    # The following options will be read by the MySQL Server. Make sure that
    # you have installed the server correctly (see above) so it reads this 
    # file.
    #
    [mysqld]# The TCP/IP Port the MySQL Server will listen on
    port=3306
    #Path to installation directory. All paths are usually resolved relative to this.
    basedir="C:/Program Files/MySQL/MySQL Server 5.0/"#Path to the database root
    datadir="C:/Program Files/MySQL/MySQL Server 5.0/Data/"# The default character set that will be used when a new schema or table is
    # created and no character set is defined
    default-character-set=gbk# The default storage engine that will be used when create new tables when
    default-storage-engine=INNODB# Set the SQL mode to strict
    sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"# The maximum amount of concurrent sessions the MySQL server will
    # allow. One of these connections will be reserved for a user with
    # SUPER privileges to allow the administrator to login even if the
    # connection limit has been reached.
    max_connections=100# Query cache is used to cache SELECT results and later return them
    # without actual executing the same query once again. Having the query
    # cache enabled may result in significant speed improvements, if your
    # have a lot of identical queries and rarely changing tables. See the
    # "Qcache_lowmem_prunes" status variable to check if the current value
    # is high enough for your load.
    # Note: In case your tables change very often or if your queries are
    # textually different every time, the query cache may result in a
    # slowdown instead of a performance improvement.
    query_cache_size=0# The number of open tables for all threads. Increasing this value
    # increases the number of file descriptors that mysqld requires.
    # Therefore you have to make sure to set the amount of open files
    # allowed to at least 4096 in the variable "open-files-limit" in
    # section [mysqld_safe]
    table_cache=256# Maximum size for internal (in-memory) temporary tables. If a table
    # grows larger than this value, it is automatically converted to disk
    # based table This limitation is for a single table. There can be many
    # of them.
    tmp_table_size=18M
    # How many threads we should keep in a cache for reuse. When a client
    # disconnects, the client's threads are put in the cache if there aren't
    # more than thread_cache_size threads from before.  This greatly reduces
    # the amount of thread creations needed if you have a lot of new
    # connections. (Normally this doesn't give a notable performance
    # improvement if you have a good thread implementation.)
    thread_cache_size=8#*** MyISAM Specific options# The maximum size of the temporary file MySQL is allowed to use while
    # recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE.
    # If the file-size would be bigger than this, the index will be created
    # through the key cache (which is slower).
    myisam_max_sort_file_size=100G# If the temporary file used for fast index creation would be bigger
    # than using the key cache by the amount specified here, then prefer the
    # key cache method.  This is mainly used to force long character keys in
    # large tables to use the slower key cache method to create the index.
    myisam_max_extra_sort_file_size=100G# If the temporary file used for fast index creation would be bigger
    # than using the key cache by the amount specified here, then prefer the
    # key cache method.  This is mainly used to force long character keys in
    # large tables to use the slower key cache method to create the index.
    myisam_sort_buffer_size=35M# Size of the Key Buffer, used to cache index blocks for MyISAM tables.
    # Do not set it larger than 30% of your available memory, as some memory
    # is also required by the OS to cache rows. Even if you're not using
    # MyISAM tables, you should still set it to 8-64M as it will also be
    # used for internal temporary disk tables.
    key_buffer_size=25M# Size of the buffer used for doing full table scans of MyISAM tables.
    # Allocated per thread, if a full scan is needed.
    read_buffer_size=64K
    read_rnd_buffer_size=256K# This buffer is allocated when MySQL needs to rebuild the index in
    # REPAIR, OPTIMZE, ALTER table statements as well as in LOAD DATA INFILE
    # into an empty table. It is allocated per thread so be careful with
    # large settings.
    sort_buffer_size=256K
    #*** INNODB Specific options ***
    # Use this option if you have a MySQL server with InnoDB support enabled
    # but you do not plan to use it. This will save memory and disk space
    # and speed up some things.
    #skip-innodb# Additional memory pool that is used by InnoDB to store metadata
    # information.  If InnoDB requires more memory for this purpose it will
    # start to allocate it from the OS.  As this is fast enough on most
    # recent operating systems, you normally do not need to change this
    # value. SHOW INNODB STATUS will display the current amount used.
    innodb_additional_mem_pool_size=2M# If set to 1, InnoDB will flush (fsync) the transaction logs to the
    # disk at each commit, which offers full ACID behavior. If you are
    # willing to compromise this safety, and you are running small
    # transactions, you may set this to 0 or 2 to reduce disk I/O to the
    # logs. Value 0 means that the log is only written to the log file and
    # the log file flushed to disk approximately once per second. Value 2
    # means the log is written to the log file at each commit, but the log
    # file is only flushed to disk approximately once per second.
    innodb_flush_log_at_trx_commit=1# The size of the buffer InnoDB uses for buffering log data. As soon as
    # it is full, InnoDB will have to flush it to disk. As it is flushed
    # once per second anyway, it does not make sense to have it very large
    # (even with long transactions).
    innodb_log_buffer_size=1M# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
    # row data. The bigger you set this the less disk I/O is needed to
    # access data in tables. On a dedicated database server you may set this
    # parameter up to 80% of the machine physical memory size. Do not set it
    # too large, though, because competition of the physical memory may
    # cause paging in the operating system.  Note that on 32bit systems you
    # might be limited to 2-3.5G of user level memory per process, so do not
    # set it too high.
    innodb_buffer_pool_size=47M# Size of each log file in a log group. You should set the combined size
    # of log files to about 25%-100% of your buffer pool size to avoid
    # unneeded buffer pool flush activity on log file overwrite. However,
    # note that a larger logfile size will increase the time needed for the
    # recovery process.
    innodb_log_file_size=24M# Number of threads allowed inside the InnoDB kernel. The optimal value
    # depends highly on the application, hardware as well as the OS
    # scheduler properties. A too high value may lead to thread thrashing.
    innodb_thread_concurrency=8[/code]
      

  2.   

    LZ您去CSDN博客搜搜很多人写了博客
    这个应该是最全的了
    http://blog.csdn.net/kelystor/archive/2007/01/23/1491184.aspx
      

  3.   

    首先你要确认中文乱码出在什么情况下
    1.出现在数据库中
    这种情况的解决方案就是吧你的数据库的编码转换为支持中文的UTF-8/GB2312就可以了
    具体怎么修改,1喽朋友已经给你写出2.出现在控制台或者前台页面
    出现这种情况的几率比较大,这也是做开发中经常遇到的情况
    解决这种情况有很多注意点:
    关键是把编码格式都统一为一种支持中文的编码格式所以你要做的就是在业务逻辑中设置一下编码格式
    就可以了
      

  4.   

    去网上找一个过滤器的java文件,其实就是一个类(class)
    然后把过滤器(Filter)的这个文件配到web.xml里去就OK,90%的乱码问题都会解决
      

  5.   

    在控制台命令行输出:set names 'utf-8';即可
      

  6.   

    mysql数据库编码有一个很烦人的地方就是插入中文时候容易产生乱码,在本文中将介绍两种解决办法!
    1在普通web项目中
      1所有jsp和servlet页面编码统一使用utf-8(或者gbk),
      2写一个过滤器package com.jin.servlet;    import java.io.IOException;   import javax.servlet.Filter;
       import javax.servlet.FilterChain;
       import javax.servlet.FilterConfig;
       import javax.servlet.ServletException;
        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;    public class Filtercode implements Filter { @Override
     public void destroy() {
      // TODO Auto-generated method stub  } @Override
     public void doFilter(ServletRequest request, ServletResponse response,
       FilterChain chain) throws IOException, ServletException {
      request.setCharacterEncoding("utf-8");
      chain.doFilter(request, response);   } @Override
     public void init(FilterConfig arg0) throws ServletException {
      // TODO Auto-generated method stub   }   }
       在配置文件web.xml中加入如下代码<filter>
        <filter-name>Filtercode</filter-name>
        <filter-class>com.jin.servlet.Filtercode</filter-class>
         </filter>
         <filter-mapping>
        <filter-name>Filtercode</filter-name>
         <url-pattern>/*</url-pattern>
         </filter-mapping>
         </web-app>
    3 数据库配置文件my.ini
      中修改默认编码gb2312(此处不能设置称utf-8,我设置称utf8时候不能启动)两处都要修改,然后在管理工具->服务中重新启动mysql@二
       在struts中数据库插入中文解决办法。
       1所有jsp设置编码utf-8,
       2数据库配置文件my.ini
      中修改默认编码gb2312(此处不能设置称utf-8,我设置称utf8时候不能启动)两处都要修改,然后在管理工具->服务中重新启动mysql
       3写个控制器
        package com.jinchun.Filter;import java.io.UnsupportedEncodingException;import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.RequestProcessor;public class MyFilter extends RequestProcessor { @Override
     protected boolean processPreprocess(HttpServletRequest request,
       HttpServletResponse response) {
      // TODO Auto-generated method stub
      try {
       request.setCharacterEncoding("utf-8");
      } catch (UnsupportedEncodingException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      
      
     return true;
      
     }}
       4在struts-config.xml中修改代码如下
    <struts-config>
      <data-sources />
      <form-beans >
       
        <form-bean name="reg1Form" type="com.jinchun.form.Reg1Form" />  </form-beans>  <global-exceptions />
      <global-forwards />
      <action-mappings >
       
        <action
          attribute="reg1Form"
          input="/reg1.jsp"
          name="reg1Form"
          path="/reg1"
          type="com.jinchun.action.Reg1Action">
          <forward
            name="fail1"
            path="/fail.jsp"
            redirect="true" />
          <forward
            name="success1"
            path="/success.jsp"
            redirect="true" />
        </action>  </action-mappings>
    <controller processorClass="com.jinchun.Filter.MyFilter"> 
    </controller>
      <message-resources parameter="com.jinchun.ApplicationResources" />
     
      <!--使用验证表单的时候一定要在form这个里面来加入  plug-in -->
       <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
            <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
                                                      /WEB-INF/validation.xml"/>
          </plug-in>
    </struts-config>本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jinchun1234/archive/2009/06/18/4280998.aspx
      

  7.   

    把从数据库读到的str
    String str = new String(str.getBytes("iso-8859-1"));
    进行转换就好了
      

  8.   

      建议使用过滤器 你是用的什么方式开发,最好是用jsp+struts+spring
      

  9.   

     这个问题我回答了N次了啊
       和你说个简单的实用的方法吧
          把latin1改成gbk,当然你想支持其他的语言如:日语和韩语,就可改成utf8      具体修改如下         [client]
             default-character-set=gbk
             port=3306         [mysql]         default-character-set=gbk       而后在81行把编码改成gbk,在重启mysql就可以了~
      

  10.   

    最好在安装时候把MySql设置成utf-8或GBK
    就没一点问题.
      

  11.   

    首先要检查你的数据存进去的时候是不是乱码
    其次就是数据库字符编码
    这个到my.ini里面去设置
     default-character-set=gbk 
    不只改这一个地方
    其他地方也需要修改
    最好是关闭之后再修改
    改完启动就没有问题了
      

  12.   

    在连接数据库的时候,加上这个代码&useUnicode=true&characterEncoding=utf-8
      

  13.   


    先看看mysql中是否支持插入中文 
    如果不支持把mysql安装文件中的my.ini里的default-character-set修改为等于gbk 然后重启mysql服务试试 
      

  14.   

    下面三项是本人总结的mysql乱码详细解决办法,没步都照着做,包你没乱码1.首先,所有页面设为UTF-8格式,包括HTML,JSP,XML,STRUTS,SPRING,HIBERNATE,如下代码
    <?xml version='1.0' encoding='UTF-8'?>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
    <title>login</title>
    </head>2.数据库设置
    ①mysql中表名的属性设置为UTF-8,字段属性设置为UTF-8
    Table Editor-Table Options-Character Set-Charset-utf8
    Table Editor-Column Details-Column Char-utf8
    ②mysql安装包里,my.ini文件,改为default-character-set=utf8;
    ③MySQL Administrator-Connection,Starup Variables,Advanced,Def.Char Set,设为utf8;
    3.加中文过滤器
    web.xml代码
    <filter>
            <filter-name>Set Character Encoding</filter-name>
            <filter-class>filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
    <filter-mapping>
            <filter-name>Set Character Encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    ***************************************************************
    filter包的CharacterEncodingFilter文件代码package filter;
    import java.io.IOException;import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;public class CharacterEncodingFilter implements Filter { protected String encoding = null; protected FilterConfig filterConfig = null; protected boolean ignore = true; public void destroy() { this.encoding = null;
    this.filterConfig = null; } public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException { if (ignore || (request.getCharacterEncoding() == null)) {
    String encoding = selectEncoding(request);
    if (encoding != null)
    request.setCharacterEncoding(encoding);
    } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig;
    this.encoding = filterConfig.getInitParameter("encoding");
    String value = filterConfig.getInitParameter("ignore");
    if (value == null)
    this.ignore = true;
    else if (value.equalsIgnoreCase("true"))
    this.ignore = true;
    else if (value.equalsIgnoreCase("yes"))
    this.ignore = true;
    else
    this.ignore = false; } protected String selectEncoding(ServletRequest request) { return (this.encoding); }}
      

  15.   

    需要配置一下你的my.ini或者my.cnf文件,只需改动一个地方就可以了。