怎么使用JDBC连接SQL Server

2024年12月02日 13:06
有2个网友回答
网友(1):

public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String connectionUrl = "jdbc:sqlserver://IP:1433;databasename=数据库";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.newInstance();
con = DriverManager.getConnection(connectionUrl, "用户", "密码");
// 调用存储过程
// CallableStatement stat = null;
// stat = con.prepareCall("{call boss(?)}");
// stat.setString(1, "0601");
// rs = stat.executeQuery();

String SQL = "select * from t_userinfo ";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
String codeid = rs.getString("u_name");
String code = rs.getString("u_pwd");
String codedesc = rs.getString("u_code");

System.out.println(codeid + code + codedesc);
}
// 打印表字段
// ResultSetMetaData rsmd = rs.getMetaData();
// int count = rsmd.getColumnCount();
// StringBuilder sBuilder = new StringBuilder();
// for (int i = 1; i <= count; i++) {
// sBuilder.append(rsmd.getColumnName(i)).append(",");
// }
// System.out.println(sBuilder.toString());

} 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 (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}

网友(2):

这个没研究过