package com.swift.erp; import java.sql.SQLException; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; public class APP { //引入 sqljdbc.jar public static void main(String[] args) { Connection conn; Statement stmt; ResultSet rs; String url = "jdbc:sqlserver://localhost:1433;DatabaseName=ecology;"; String sql = "select * from hrmresource"; try { // 连接数据库 conn = DriverManager.getConnection(url, "sa", "1"); // 建立Statement对象 stmt = conn.createStatement(); /** * Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。 */ // 执行数据库查询语句 rs = stmt.executeQuery(sql); /** * ResultSet executeQuery(String sql) throws SQLException 执行给定的 SQL * 语句,该语句返回单个 ResultSet 对象 */ while (rs.next()) { int id = rs.getInt("id"); String loginid = rs.getString("loginid"); String lastname = rs.getString("lastname"); System.out.println("id:" + id + "loginid:" + loginid + "lastname:" + lastname); } 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(); System.out.println("数据库连接失败"); } } }
标签:jdbc,java,String,rs,sql,null,mssql,conn From: https://www.cnblogs.com/hua900822/p/17356857.html