从简单的java连接MSSQLSERVER代码中得到的教训

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
String sqlUrl = "jdbc:sqlserver://127.0.0.1:1433;databaseName=Test;user=sa;password=sa";

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(sqlUrl);

// Create and execute an SQL statement that returns some data.
String SQL = "select * from tableName";
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);

ResultSet excel = readExcel();

while (excel.next())
System.out.println(excel.getString(2));

}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
}
if (conn != null)
try {
conn.close();
} catch (Exception e) {
}
}

一切都没什么好说的,只有那句:**System.out.println(excel.getString(2));**

最初写的是getString(0),一直报错,怎么写也报错,getArray,getObject都试了一遍,还是报错:

java.sql.SQLException: [Microsoft][ODBC
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLColAttributes(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getColAttribute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getColumnType(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getMaxCharLen(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at com.lison.practise.Main.main(Main.java:39)

最后是查看了getString的源码,看到了注解:

ResultSet的getString方法注解

原来这个index是从1开始的, 瞬间清凉到北极啊。。。尼玛不看注解会折寿啊。。。