Я пытаюсь использовать драйвер jdbc для сервера Microsoft SQL для подключения к моей базе данных, но мне удается установить соединение с сервером, однако происходят некоторые странные вещи. Вот мой класс Dconnector:
package com.myblog;
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
import java.sql.*;
import java.util.Properties;
public class Dconnector {
public Connection connection = null;
public Statement stmt;
static Properties prop = null;
public Dconnector() throws SQLException {
DriverManager.registerDriver(new SQLServerDriver());
System.out.println("SQL JDBC Connection Testing");
prop = new Properties();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String DB_CONN_STRING = "jdbc:sqlserver://localhost:1434;databaseName=blogdb;";
//Provided by your driver documentation. In this case, a MySql driver is used :
String USER_NAME = "sa";
String PASSWORD = "pwd";
connection =DriverManager.getConnection(DB_CONN_STRING, USER_NAME, PASSWORD);
stmt = connection.createStatement();
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connected!");
} else {
System.out.println("Failed to connect!");
}
}
public ResultSet queryResult(String Query) {
ResultSet rst = null;
try {
rst = stmt.executeQuery(Query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
}
public int queryCount(String Query) {
int count = 0;
try {
count = stmt.executeUpdate(Query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
public void closeConnection()
{
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Что странно, так это то, что когда я запускаю веб-приложение и создаю новый экземпляр Dconnector, вот так:
com.myblog.Dconnector db=new com.myblog.Dconnector();
И закройте его:
db.closeConnection();
Почему-то кажется, что класс завязан 3 раза? В консоли «SQL JDBC Connection Testing», затем «Connected!» отображается 3 раза.
Также, когда я пытаюсь вызвать queryResult с любым запросом между открытием соединения и закрытием всех разрывов ада с ошибкой чтения ответа prelogin и сброс соединения повторяется снова 3 раза.
Вот код, используемый в файле .jsp (сценарий):
com.myblog.Dconnector db=new com.myblog.Dconnector();
ResultSet rst=db.queryResult("SELECT Caption FROM ArticlesTB");
ResultSetMetaData rsmd = rst.getMetaData();
int columnsNumber = rsmd.getColumnCount();
try {
while (rst.next()) {
for (int i = 1; i <= columnsNumber; i++) {
String columnValue = rst.getString(i);
System.out.print("<h1>" +columnValue + "
</h1>"+System.getProperty("line.separator"));
}
}}
catch (SQLException e)
{
e.printStackTrace();
System.out.println("This did not work");
}
db.closeConnection();
Сейчас я просто вывожу на консоль для тестирования. Соответствующая часть вывода консоли следующая:
Connected to server
[2018-09-05 11:53:39,507] Artifact Stranka:war exploded: Artifact is being
deployed, please wait...
05-Sep-2018 23:53:40.372 INFO [RMI TCP Connection(3)-127.0.0.1]
org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned
for TLDs yet contained no TLDs. Enable debug logging for this logger for a
complete list of JARs that were scanned but no TLDs were found in them.
Skipping unneeded JARs during scanning can improve startup time and JSP
compilation time.
[2018-09-05 11:53:40,435] Artifact Stranka:war exploded: Artifact is deployed
successfully
[2018-09-05 11:53:40,435] Artifact Stranka:war exploded: Deploy took 928
milliseconds
-------- SQL JDBC Connection Testing ------------
You made it, take control your database now!
(h1)This is a sample article(/h1)
(h1)This is a second article.(/h1)
(h1)This is a third sample.(/h1)
-------- SQL JDBC Connection Testing ------------
You made it, take control your database now!
(h1)This is a sample article(/h1)
(h1)This is a second article.(/h1)
(h1)This is a third sample.(/h1)
-------- SQL JDBC Connection Testing ------------
You made it, take control your database now!
(h1)This is a sample article(/h1)
(h1)This is a second article.(/h1)
(h1)This is a third sample.(/h1)
05-Sep-2018 23:53:49.219 INFO
[ContainerBackgroundProcessor[StandardEngine[Catalina]]]
org.apache.catalina.startup.HostConfig.deployDirectory Deploying web
application directory [C:\apache-tomcat-9.0.11\webapps\manager]
05-Sep-2018 23:53:49.312 INFO
[ContainerBackgroundProcessor[StandardEngine[Catalina]]]
org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web
application directory [C:\apache-tomcat-9.0.11\webapps\manager] has finished
in [93] ms
HTML-теги были отредактированы для поддержки формата кода.