日期:2014-05-18  浏览次数:20651 次

菜鸟问题,希望帮助
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*,java.util.*"%>

<%!
Connection conn;
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb","sa","123456");
}
%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charsetGB2312">
<title>dbconn</title>
</head>
<body>
<%

Statement stmt=conn.createStatement();
String sql="select * from [USERS]";
ResultSet rs=stmt.executeQuery(sql);
while (rs.next()) {%>
  第一个字段内容为:<%=rs.getString("username")%>
  第二个字段内容为:<%=rs.getString("password")%>
  第二个字段内容为:<%=rs.getString("Intro")%><br>
<%}%>
<%out.print("数据库操作成功!");%>
<%rs.close();
  stmt.close();
  conn.close();%>
</body>
</html>




改成下面的话就出错:





<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*,java.util.*"%>
<%! //提示出错的地方
public Connection conndb(){
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
Connection conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb","sa","123456");
return conn;
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charsetGB2312">
<title>dbconn</title>
</head>
<body>
<%
Connection conn;
conn=conndb();
Statement stmt=conn.createStatement();
String sql="select * from [USERS]";
ResultSet rs=stmt.executeQuery(sql);
while (rs.next()) {%>
  第一个字段内容为:<%=rs.getString("username")%>
  第二个字段内容为:<%=rs.getString("password")%>
  第二个字段内容为:<%=rs.getString("Intro")%><br>
<%}%>
<%out.print("数据库操作成功!");%>
<%rs.close();
  stmt.close();
  conn.close();%>
</body>
</html>

------解决方案--------------------
楼主试试,没验证过

Java code
<%@ page contentType="text/html;charset=GB2312" %> 
<%@ page import="java.sql.*,java.util.*"%> 
<%! //提示出错的地方 
class test{
public static Connection conndb(){ 
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); 
Connection conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb","sa","123456"); 
return conn; 
} 
}
%> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charsetGB2312"> 
<title>dbconn </title> 
</head> 
<body> 
<% 
Connection conn; 
conn=test.conndb(); 
Statement stmt=conn.createStatement(); 
String sql="select * from [USERS]"; 
ResultSet rs=stmt.executeQuery(sql); 
while (rs.next()) {%> 
  第一个字段内容为: <%=rs.getString("username")%> 
  第二个字段内容为: <%=rs.getString("password")%> 
  第二个字段内容为: <%=rs.getString("Intro")%> <br> 
<%}%> 
<%out.print("数据库操作成功!");%> 
<%rs.close(); 
  stmt.close(); 
  conn.close();%> 
</body> 
</html>

------解决方案--------------------<