使用多行sql字符串时,要注意不要忽略了空格

使用李刚老师编著的《疯狂Java讲义》(第2版)学习MySql数据库与JDBC编程(使用Java 7 ),其中第601页的ConnMySql.java 程序代码在Eclipse上运行,出现错误。

import java.sql.*;
public class ConnMySql{
    public static void main(String[] args)throws Exception
    {
        Class.forName("com.mysql.jdbc.Driver");
        try(
            Connection conn = DriverManager.getConnection(
                "jdbc:mysql://127.0.0.1:3306/select_test"
                ,"root","0754"
            );
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery( "select s.* ,teacher_name"
                + "from student_table s, teacher_table t" 
                + "where t.teacher_id = s.java_teacher"))//这里出错
            
                {
                    while(rs.next()){
                        System.out.println(rs.getInt(1) + "\t"
                            + rs.getString(2) + "\t"
                            + rs.getString(3) + "\t"
                            + rs.getString(4) );
                        }
                    }
        }
    }

根据提示把Sql语句从原来的使用双引号将多行语句连接起来改为一行语句,编译通过。

import java.sql.*;
public class ConnMySql{
    public static void main(String[] args)throws Exception
    {
        Class.forName("com.mysql.jdbc.Driver");
        /*
         * 采用了自动关闭资源的try语句来关闭各种数据库资源,,Java7改写了Connection、Statement、ResultSet等接口,
         * 它们都继承了AutoCloseable接口,因此它们都可以用try语句来关闭。
         * 
         * */
        try(
            Connection conn = DriverManager.getConnection(
                "jdbc:mysql://127.0.0.1:3306/select_test"
                ,"root","0754"
            );
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select s.* ,teacher_name from student_table s, teacher_table t where t.teacher_id = s.java_teacher" ))//这样改就没问题
            /*
             * "select s.* ,teacher_name"
                + "from student_table s, teacher_table t" 
                + "where t.teacher_id = s.java_teacher"
             * */
                {
                    while(rs.next()){
                        System.out.println(rs.getInt(1) + "\t"
                            + rs.getString(2) + "\t"
                            + rs.getString(3) + "\t"
                            + rs.getString(4) );
                        }
                    }
        }
    }

仔细查看代码后发现,每一句跟下一句句首都没有留空格,相当于

select s.* ,teacher_namefrom student_table s, teacher_table t"

所以导致出错。

但是尝试先在ResultSet语句上边定义String类型变量s,会提示“The resource type String does not implement java.lang.AutoCloseable”。在try语句前定义就没问题。

 

posted on 2013-02-15 15:04  JLeight  阅读(554)  评论(0编辑  收藏  举报

导航