当Java与MySQL进行连接时,其返回结果中的汉字老是乱码!这是为什么.请各位热爱祖国的朋友们帮个忙!以下是进行连接时的源码:(注:其中有两个文件:ViewDB.java、database.properties)1.database.properties文件jdbc.drivers=org.gjt.mm.mysql.Driver
jdbc.url=jdbc:mysql://localhost/你的数据库名
jdbc.username=您的用户名
jdbc.password=你的密码

解决方案 »

  1.   

    2.ViewDB.java文件/**
       @version 1.30 2004-08-05
       @author Cay Horstmann
    */import java.net.*;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;/**
       This program uses metadata to display arbitrary tables
       in a database.
    */
    public class ViewDB
    {  
       public static void main(String[] args)
       {  
          JFrame frame = new ViewDBFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       }
    }/**
       The frame that holds the data panel and the navigation 
       buttons.
    */
    class ViewDBFrame extends JFrame
    {
       public ViewDBFrame()
       {  
          setTitle("ViewDB");
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);      tableNames = new JComboBox();
          tableNames.addActionListener(new
             ActionListener()
             {
                public void actionPerformed(ActionEvent event)
                {
                   showTable((String) tableNames.getSelectedItem());
                }
             });
          add(tableNames, BorderLayout.NORTH);      try
          {  
             conn = getConnection();         
             meta = conn.getMetaData();
             createStatement();
             getTableNames();
          }
          catch (SQLException e)
          {  
             JOptionPane.showMessageDialog(this, e);
          }
          catch (IOException e)
          {  
             JOptionPane.showMessageDialog(this, e);
          }            JPanel buttonPanel = new JPanel();
          add(buttonPanel, BorderLayout.SOUTH);      if (scrolling)
          {
             previousButton = new JButton("Previous");
             previousButton.addActionListener(new
                ActionListener()
                {
                   public void actionPerformed(ActionEvent event)
                   {
                      showPreviousRow();
                   }
                });
             buttonPanel.add(previousButton);
          }      nextButton = new JButton("Next");
          nextButton.addActionListener(new
             ActionListener()
             {
                public void actionPerformed(ActionEvent event)
                {
                   showNextRow();
                }
             });
          buttonPanel.add(nextButton);      addWindowListener(new
             WindowAdapter()
             {  
                public void windowClosing(WindowEvent event)
                {  
                   try
                   {                   
                      if (conn != null) conn.close();
                   }
                   catch (SQLException e) 
                   {
                      while (e != null)
                      {
                         e.printStackTrace();
                         e = e.getNextException();
                      }
                   }
                }
            });
       }   /**
          Creates the statement object used for executing queries.
          If the database supports scrolling cursors, the statement
          is created to yield them.
       */
       public void createStatement() throws SQLException
       {
          if (meta.supportsResultSetType(
             ResultSet.TYPE_SCROLL_INSENSITIVE))
          {
             stat = conn.createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE, 
                ResultSet.CONCUR_READ_ONLY);
             scrolling = true;
          }
          else
          {
             stat = conn.createStatement();
             scrolling = false;
          }
       }
       
       /**
          Gets all table names of this database and adds them
          to the combo box.
       */
       public void getTableNames() throws SQLException
       {
          ResultSet mrs = meta.getTables(null, null, null, new String[] { "TABLE" });
          while (mrs.next())
             tableNames.addItem(mrs.getString(3));
          mrs.close();
       }   /**
          Prepares the text fields for showing a new table, and
          shows the first row.
          @param tableName the name of the table to display
       */
       public void showTable(String tableName)
       {  
          try
          {  
             if (rs != null) rs.close();
             rs = stat.executeQuery("SELECT * FROM " + tableName);
             if (scrollPane != null) 
                remove(scrollPane);
             dataPanel = new DataPanel(rs);
             scrollPane = new JScrollPane(dataPanel);
             add(scrollPane, BorderLayout.CENTER);
             validate();
             showNextRow();
          }
          catch (SQLException e)
          {  
             JOptionPane.showMessageDialog(this, e);
          }
       }   /**
          Moves to the previous table row.
       */
       public void showPreviousRow()
       {  
          try
          {  
             if (rs == null || rs.isFirst()) return;
             rs.previous();
             dataPanel.showRow(rs);
          }
          catch (SQLException e)
          {  
             JOptionPane.showMessageDialog(this, e);
          }      
       }   /**
          Moves to the next table row.
       */
       public void showNextRow()
       {  
          try
          {  
             if (rs == null || scrolling && rs.isLast()) return;         if (!rs.next() && !scrolling) 
             { 
                rs.close(); 
                rs = null; 
                return; 
             }         dataPanel.showRow(rs);
          }
          catch (SQLException e)
          {  
             JOptionPane.showMessageDialog(this, e);
          }      
       }   /**
          Gets a connection from the properties specified
          in the file database.properties
          @return the database connection
       */
       public static Connection getConnection()
          throws SQLException, IOException
       {  
          Properties props = new Properties();
          FileInputStream in 
             = new FileInputStream("database.properties");
          props.load(in);
          in.close();      String drivers = props.getProperty("jdbc.drivers");
          if (drivers != null) System.setProperty("jdbc.drivers", drivers);
          String url = props.getProperty("jdbc.url");
          String username = props.getProperty("jdbc.username");
          String password = props.getProperty("jdbc.password");      return DriverManager.getConnection(url, username, password);
       }   public static final int DEFAULT_WIDTH = 300;
       public static final int DEFAULT_HEIGHT = 200;     private JButton previousButton;
       private JButton nextButton;
       private DataPanel dataPanel;
       private Component scrollPane;
       private JComboBox tableNames;   private Connection conn;
       private Statement stat;
       private DatabaseMetaData meta;
       private ResultSet rs;
       private boolean scrolling;
    }/**
       This panel displays the contents of a result set.
    */
    class DataPanel extends JPanel
    {
       /**
          Constructs the data panel.
          @param rs the result set whose contents this panel displays
       */
       public DataPanel(ResultSet rs) throws SQLException
       {
          fields = new ArrayList<JTextField>();
          setLayout(new GridBagLayout());
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridwidth = 1;
          gbc.gridheight = 1;      ResultSetMetaData rsmd = rs.getMetaData();
          for (int i = 1; i <= rsmd.getColumnCount(); i++)
          {  
             gbc.gridy = i - 1;         String columnName = rsmd.getColumnLabel(i);
             gbc.gridx = 0;
             gbc.anchor = GridBagConstraints.EAST;
             add(new JLabel(columnName), gbc);         int columnWidth = rsmd.getColumnDisplaySize(i);
             JTextField tb = new JTextField(columnWidth);
             fields.add(tb);         gbc.gridx = 1;
             gbc.anchor = GridBagConstraints.WEST;
             add(tb, gbc);
          }      
       }   /**
          Shows a database row by populating all text fields
          with the column values.
       */
       public void showRow(ResultSet rs) throws SQLException
       {  
          for (int i = 1; i <= fields.size(); i++)
          {  
             String field = rs.getString(i);
             JTextField tb = (JTextField) fields.get(i - 1);
             tb.setText(field);
          }
       }   private ArrayList<JTextField> fields;
    }
      

  2.   

    jdbc.drivers=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost/你的数据库名?useUnicode=true&characterEncoding=GBK
    jdbc.username=您的用户名
    jdbc.password=你的密码org.gjt.mm.mysql.Driver,这个驱动 MySQL 很早就不建议使用了确保数据库的编码格式是 GBK,如果不是可以更改 %MySQL_HOME%/my.ini 的 [mysqld],
    加上 default-character-set=GBK 一句,以后新建的数据库都是以 GBK 编码的。
      

  3.   

    关于mysql数据库乱码问题很常见
    网上一搜一大堆解决之前应该先确实你数据库编码,页面编码不过为了减少编码问题带来的麻烦
    现在都推荐尽量都采用utf-8编码
      

  4.   

    org.gjt.mm.mysql.Driver,这个驱动 MySQL 很早就不建议使用了一>com.mysql.jdbc.Driver
      

  5.   

    使用mysql缺省的安装、新建数据库,插入的表后用link查看正常显示,但是在页面里却显示乱码。连接字符串使用了characterEncoding=gb2312,依然是乱码,怀疑是mysql数据库的问题。修改my.ini里default-character-set=gb2312。然后重新新建数据库,新建的时候选择gb2312数据集。一切ok了。
      

  6.   

    set   character_set_result=gbk
      

  7.   

    本文以最常见的JSP+MySQL+Tomcat+Apache乱码解决为例,望能为你的环境配置起到抛砖引玉之效!  乱码问题已历来已久,在开源环境下,乱码问题更是令程序员措手不及。本人在Unix(Freebsd)下的一次乱码经历可谓经典,故撰以此文以滋效尤!  我将本次所遇乱码归为三类:  1.页面字符乱码  2.记录显示乱码  3.request传递乱码  以下将对上述三类乱码进行解析:一.页面字符乱码:  1.大小写不一致:org.apache.jasper.JasperException: /top.jsp(1,1) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html;charset=gb2312, new: text/html;charset=GB2312)  2.间隔不一致:org.apache.jasper.JasperException: /top.jsp(1,1) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html; charset=GB2312, new: text/html;charset=GB2312)*解决方案:首先,在Apache中增加AddDefaultCharset GB2312或AddDefaultCharset GBK其次,统一使用页面编码定义,如:<%@page contentType="text/html;charset=GB2312"%>*注:GB2312为GBK之子集。二.记录显示乱码:  1.MySQL默人语言为latin1_swedish_ci,即拉丁语,所以取出的中文全是乱码。*解决方案:  1.将charset设为8859_1即:<%@page contentType="text/html;charset=8859_1"%>  这个方法只能暂时缓解字符显示问题,并权益之计。因为8859_1为字节型字库,并非字型字库,故在非全角状态下,将出现半字乱码,表现为“?”。  2.在数据库连接语句中加上?useUnicode=true;characterEncoding=GBK,如:
    jdbc:mysql://localhost/dbname?useUnicode=true;characterEncoding=GBK*注:一般教科书上都会加上localhost:3306,因为默认端口为3306,故可舍去!同时,请使用连接池的朋友注意,在注册xml文件时,是不可以单独出现“;”的,所以必须使用“&amp;”,即:jdbc:mysql://localhost/dbname?useUnicode=true&amp;characterEncoding=GBK。  否则提示出错:Parse Fatal Error at line 213 column 91: The reference to entity "characterEncoding" must end with the ';' delimiter.
    org.xml.sax.SAXParseException: The reference to entity "characterEncoding" must
    end with the ';' delimiter.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Un
    known Source)  也曾有人提意:在MySQL的my.ini文件中加入default-character-set=gbk,本人不赞同此法,因为这样破坏了原有的环境,除非这是MySQL的第一个站点。三.request传递乱码:  1.也许,此时你已经可以正常使用系统了,那么恭喜~乱码问题已经离开你了!但是,大伙通常都没那么走运,乱码问题依旧存在。也许,这时你向数据库添加了一条记录以测试系统,可是此时显示出的还是乱码。那么可以肯定是Request参数传递出错!那么先写个测试语句:<%= request.getParameter(“Para”) %>,OK,果然是乱。那么,现在有两种解决方法。*解决方案:  1.加上这条语句:request.setCharacterEncoding("gbk");
    在一/两页上可行,但此法也非权益之计。  2.注册SetCharacterEncodingFilter类:  首先,编写SetCharacterEncodingFilter.java文件,代码如下:package cn.com.jsp;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;
    import javax.servlet.UnavailableException;public class SetCharacterEncodingFilter 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 {        // Conditionally select and set the character encoding to be used
            if (ignore || (request.getCharacterEncoding() == null)) {
                String encoding = selectEncoding(request);
                if (encoding != null) {
                    request.setCharacterEncoding(encoding);
                }
            }        // Pass control on to the next filter
            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);
        }}  此文件为request过滤类,在全局编译前需进行注册。  注册文件为:<%wwwroot%>/WEB-INF/web.xml。  在此文件中加入如下代码即可:<web-app>
      <display-name>wwwroot</display-name>
      <description>MySQL Test App</description>
      <filter>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <display-name>setCharacterEncodingFilter</display-name>
        <description>setCharacterEncodingFilter</description>
        <filter-class>cn.com.jsp.SetCharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>GBK</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    ……
    </web-app>  OK,现在可以编译你的SetCharacterEncodingFilter.java文件啦!  至此,乱码将与你格格不入! 
      

  8.   

    安装mysql时的默认字符集是latin1,你可以使用mysql自带的修复工具将数据库字符集改为gbk(选择修复工具,一直点Next到数据库字符集项把字符集改过来),也可以在mysql的配置文件中进行修改。。不过就是比较麻烦。
      

  9.   

    MYSQL安装的时候就要选定语言为GBK
      

  10.   

    当我把my.ini文件中的default-character-set=latin1改为default-character-set=GBK后。再去查询已经存在的数据库中的数据时,在查询的结果中却出现了“???……”之类的乱码!
    这是怎么一回事!有那们朋友知道。(必重分感谢)