您的位置:程序门 -> java -> j2se / 基础类



java与mysql连接的问题!


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


java与mysql连接的问题!
发表于:2007-10-10 11:16:02 楼主
当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=你的密码
发表于:2007-10-10 11:17:391楼 得分:0
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;
}
发表于:2007-10-10 11:59:562楼 得分:0
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   编码的。
发表于:2007-10-10 12:00:233楼 得分:0
把错贴出来!
发表于:2007-10-10 12:20:494楼 得分:0
关于mysql数据库乱码问题很常见
网上一搜一大堆

解决之前应该先确实你数据库编码,页面编码

不过为了减少编码问题带来的麻烦
现在都推荐尽量都采用utf-8编码
发表于:2007-10-10 13:31:455楼 得分:0
org.gjt.mm.mysql.driver,这个驱动   mysql   很早就不建议使用了

一> com.mysql.jdbc.driver
发表于:2007-10-10 13:33:256楼 得分:0
使用mysql缺省的安装、新建数据库,插入的表后用link查看正常显示,但是在页面里却显示乱码。连接字符串使用了characterencoding=gb2312,依然是乱码,怀疑是mysql数据库的问题。修改my.ini里default-character-set=gb2312。然后重新新建数据库,新建的时候选择gb2312数据集。一切ok了。
发表于:2007-10-10 13:34:007楼 得分:0
set       character_set_result=gbk
发表于:2007-10-10 13:34:478楼 得分:0
本文以最常见的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文件啦!

  至此,乱码将与你格格不入!  
发表于:2007-10-10 22:25:119楼 得分:0
非常感谢各位!待五天后,立即结帖
发表于:2007-10-10 22:35:0110楼 得分:0
也可以修改mysql的默认语言
发表于:2007-10-10 22:40:1211楼 得分:0
安装mysql时的默认字符集是latin1,你可以使用mysql自带的修复工具将数据库字符集改为gbk(选择修复工具,一直点next到数据库字符集项把字符集改过来),也可以在mysql的配置文件中进行修改。。不过就是比较麻烦。
发表于:2007-10-11 00:15:1712楼 得分:0
mysql安装的时候就要选定语言为gbk
发表于:2007-10-11 22:21:5613楼 得分:0
当我把my.ini文件中的default-character-set=latin1改为default-character-set=gbk后。再去查询已经存在的数据库中的数据时,在查询的结果中却出现了“???……”之类的乱码!
这是怎么一回事!有那们朋友知道。(必重分感谢)


快速检索

最新资讯
热门点击