Home  >  Article  >  Database  >  java与Oracle异常中的乱码

java与Oracle异常中的乱码

WBOY
WBOYOriginal
2016-06-07 17:45:311657browse

/*
 * Test.java 2008-7-30
 *
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

import oracle.jdbc.OracleDriver;

public class Test {
    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver(new OracleDriver());
       
        // 正常
        Connection conn = getConnection();
        ResultSet rs = conn.createStatement().executeQuery(
                app2db("SELECT '123abc我是谁?' FROM DUAL"));
        rs.next();
        // 打印123abc我是谁?
        System.out.println(db2app(rs.getString(1)));
       
        // 异常
        // 因该打印ORA-00921: unexpected end of SQL command
        // 结果打印ORA-00921: ???? SQL ????
        try {
            conn.createStatement().executeQuery("SELECT 1 FROM DUAL WHERE");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        // 因该打印ORA-00920: invalid relational operator
        // 结果打印ORA-00920: ????????
        try {
            conn.createStatement().executeQuery("SELECT 1 FROM DUAL WHERE 1");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        // 因该打印ORA-00904: "X": invalid identifier
        // 结果打印ORA-00904: "X": ??????
        try {
            conn.createStatement().executeQuery("SELECT x FROM x");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static String app2db(String str) throws Exception {
        return new String(str.getBytes(), "ISO-8859-1");
    }

    private static String db2app(String str) throws Exception {
        return new String(str.getBytes("ISO-8859-1"));
    }

    private static Connection getConnection() throws Exception {
        return DriverManager.getConnection("jdbc:oracle:thin:......");
    }
}

解决方法:

你可以考虑设置Oracle客户端所在的机器(也是你的应用程序运行的机器)的NLS_LANG环境变量来绕开这个问题

我在自己的机器上做了个测试,效果如下:

系统环境

Windows 2003简体中文版,Oracle 10g

操作步骤

1.执行cmd.exe开启一个命令行窗口
2.执行sqlplus username/password进入SQL Plus命令提示符
3.执行如下SQL语句
Sql代码
select 'x' from dua; 

select 'x' from dua;
注意dua是我故意写错的(dual少了其中的l),以便得到一个oracle异常
这时可以看到错误信息如下:

引用
第 1 行出现错误:
ORA-00942: 表或视图不存在

4.执行quit退出SQL Plus命令提示符
5.在操作系统命令行提示符执行如下命令
Java代码
set nls_lang=AMERICAN_AMERICA.WE8ISO8859P1 

set nls_lang=AMERICAN_AMERICA.WE8ISO8859P1
6.重复第2、3步骤
这时可以看到错误信息如下:

引用
ERROR at line 1:
ORA-00942: table or view does not exist


可以看到,原来输出的错误信息是中文的,设置后错误信息为英文的了。这正是你需要的

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn