当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=你的密码
jdbc.url=jdbc:mysql://localhost/你的数据库名
jdbc.username=您的用户名
jdbc.password=你的密码
@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;
}
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 编码的。
网上一搜一大堆解决之前应该先确实你数据库编码,页面编码不过为了减少编码问题带来的麻烦
现在都推荐尽量都采用utf-8编码
jdbc:mysql://localhost/dbname?useUnicode=true;characterEncoding=GBK*注:一般教科书上都会加上localhost:3306,因为默认端口为3306,故可舍去!同时,请使用连接池的朋友注意,在注册xml文件时,是不可以单独出现“;”的,所以必须使用“&”,即:jdbc:mysql://localhost/dbname?useUnicode=true&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文件啦! 至此,乱码将与你格格不入!
这是怎么一回事!有那们朋友知道。(必重分感谢)