62,614
社区成员
发帖
与我相关
我的任务
分享
import java.sql.*;
import java.util.Vector;
public class TestJdbcsqlServer {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("实例化成功 is ok!!");
// 你这步出现了异常,但是你写的没有错,看异常报的是建立socket错误,你有没有打上SQLServer 2000
// 的sp4的补丁?或者是你端口号是否正确?
conn = DriverManager
.getConnection(
"jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=factory",
"sa", "sa");
System.out.println("the connection is ok!!");
Vector<String> fieldNames = new Vector<String>();
DatabaseMetaData metaData = conn.getMetaData();
rs = metaData.getColumns(null, null, "employee", null);
while (rs.next()) {
fieldNames.addElement(rs.getString(4) + "\t\t|");
}
System.out.print("Table employee:\n|");
for (int i = 0; i < fieldNames.size(); i++) {
System.out.print(fieldNames.elementAt(i));
}
System.out.println();
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from employee order by id asc");
while (rs.next()) {
System.out.print("|");
for (int i = 1; i <= fieldNames.size(); i++) {
System.out.print(rs.getString(i) + "\t|");
}
System.out.println();
}
} catch (ClassNotFoundException e) {
System.out
.println("com.microsoft.jdbc.sqlserver.SQLServerDriver Is Not Found!!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLSata: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}