我使用JTDS连接到MS SQL Server。连接到数据库没有问题,但是当我尝试执行一个语句时,我得到了一个数据库' java'不存在例外。
的ConnectionString:
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost;DatabaseName=MyDatabase;user=testuser;password=testpassword");
尝试执行脚本:
private void runStatement(String scriptLocation) {
if(scriptLocation == null) {
return;
}
try {
InputStream is = getClass().getClassLoader().getResourceAsStream(scriptLocation);
String query = is.toString();
is.close();
Statement stmt = conn.createStatement();
stmt.executeQuery(query);
} catch(IOException | SQLException ex) {
log.warning(ex.getMessage());
}
}
堆栈跟踪:
WARNING: Database 'java' does not exist. Make sure that the name is entered correctly.
java.sql.SQLException: Database 'java' does not exist. Make sure that the name is entered correctly.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeQuery(JtdsStatement.java:1427)
at com.exampe.MyJTDSConnection.runStatement(MyJTDSConnection.java:238)
at com.exampe.MyJTDSConnection.loadPageTitle(MyJTDSConnection.java:208)
at com.exampe.MyJTDSConnection.runTesting(MyJTDSConnection.java:69)
at com.exampe.SeleniumTesting.runTest(SeleniumTesting.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
答案 0 :(得分:1)
如您对问题的评论中所述,将.toString()
方法应用于InputStream对象不会读取InputStream。相反,它只返回对象本身的String表示,而不是对象包含的内容。
例如,我的Java项目有一个名为" script.sql"的资源文件。包含:
SELECT @@VERSION
以下代码比较了简单地在对象上使用.toString()
与使用Apache Commons IO实际读取将InputStream转换为字符串的结果:
package resourceTest;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
public class ResourceTestMain {
public static void main(String[] args) {
try (InputStream is = ResourceTestMain.class.getClassLoader().getResourceAsStream("resources/script.sql")) {
String toStringValue = is.toString();
String contents = IOUtils.toString(is, "UTF-8");
is.close();
System.out.println("is.toString() returned:");
System.out.println(" " + toStringValue);
System.out.println();
System.out.println("IOUtils.toString(is, \"UTF-8\") returned:");
System.out.println(" " + contents);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
结果是:
is.toString() returned:
java.io.BufferedInputStream@804a77
IOUtils.toString(is, "UTF-8") returned:
SELECT @@VERSION