SQL Server RUNS ON Java应用程序但不是WEB应用程序(SERVLET)NETBEANS有什么问题?
答案 0 :(得分:-1)
我在这个项目中学习Web编程课程我遇到了很多错误。问题中讨论了一个令人印象深刻的错误。我找到了问题的解决方案。
对于在Netbeans中创建的Java应用程序此代码运行良好,不能在Web应用程序Java类中运行:
import java.sql.*;
/**
*
* @author HafizAhmad
*/
public class SQLConnection {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Connection conn = null;
try {
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Flight_Management";
String user = "TestingUser";
String pass = "4546";
conn = DriverManager.getConnection(dbURL,user,pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
但是在Web应用程序中我首先在源包中创建java类,然后将代码更改为:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author HafizAhmad
*/
public class database {
database(){
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Flight_Management";
String user = "TestingUser";
String pass = "4546";
conn = DriverManager.getConnection(dbURL,user,pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(page.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}