连接JDBC时出错 - 使用JSP的MYSQL

时间:2014-01-23 10:00:12

标签: jsp

<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%
public static **Connection connectToDB()**
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll", "root","");

        }
        catch(Exception e)
        {
            System.out.println("Error: "+e);    
        }
    }

    public static boolean **closeConnection(Connection c)**
    {
        try
        {
        c.close();
        return true;
        }
        catch (Exception e)
        {
        return false;
        }
    }
%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Connection c=new connectToDB();
out.print(c);
close(c);
%>
</body>
</html>

//这些函数中的以下错误以粗体显示。

Multiple annotations found at this line:
    - Line breakpoint:index.jsp [line: 4]
    - Syntax error, insert "enum Identifier" to complete 
     EnumHeaderName
    - Syntax error, insert "EnumBody" to complete BlockStatement
    - Syntax error on token "Connection", @ expected


Multiple annotations found at this line:
    - Syntax error on token ")", ; 
     expected
    - Syntax error on token "(", ; 
     expected

1 个答案:

答案 0 :(得分:0)

当你使用&lt;%语法时,这意味着你正在使用一个scriptlet,因为你可能知道所有jsp的页面都被翻译并编译成一个servlet,当你使用一个scriptlet时,这个代码放在了服务方法的内部。 servlet,如果你使用scriptlet来定义一个新方法就像你在另一个方法中创建一个新方法,所以你需要使用声明语法&lt;%!这允许在转换的servlet类中声明变量或方法,代码在服务方法之外,并将此声明放在页面指令之后:

<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
public static **Connection connectToDB()**
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll", "root","");

        }
        catch(Exception e)
        {
            System.out.println("Error: "+e);    
        }
    }

    public static boolean **closeConnection(Connection c)**
    {
        try
        {
        c.close();
        return true;
        }
        catch (Exception e)
        {
        return false;
        }
    }
%>
<%
Connection c=new connectToDB();
out.print(c);
close(c);
%>
</body>
</html>