标签:连接失败 对象 imp exce tac sql java res man
1 import java.sql.Connection; 2 import java.sql.SQLException; 3 import java.sql.Statement; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 7 8 public class JavaE2 { 9 public static void main(String[] args) { 10 Connection conn; 11 Statement stmt; 12 ResultSet rs; 13 String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;"; 14 String sql = "select * from student"; 15 16 17 try { 18 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 19 20 } catch (Exception ex) { 21 System.out.println("数据库加载失败"); 22 } 23 24 25 try { 26 // 连接数据库 27 conn = DriverManager.getConnection(url, "sa", "sa"); 28 // 建立Statement对象 29 stmt = conn.createStatement(); 30 /** 31 * Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。 32 */ 33 // 执行数据库查询语句 34 rs = stmt.executeQuery(sql); 35 /** 36 * ResultSet executeQuery(String sql) throws SQLException 执行给定的 SQL 37 * 语句,该语句返回单个 ResultSet 对象 38 */ 39 while (rs.next()) { 40 int id = rs.getInt("SID"); 41 String name = rs.getString("SNAME"); 42 int age = rs.getInt("SSEX"); 43 System.out.println("Sno:" + id + "\tSame:" + name + "\tSage:" + age); 44 } 45 if (rs != null) { 46 rs.close(); 47 rs = null; 48 } 49 if (stmt != null) { 50 stmt.close(); 51 stmt = null; 52 } 53 if (conn != null) { 54 conn.close(); 55 conn = null; 56 } 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 System.out.println("数据库连接失败"); 60 } 61 } 62 }
标签:连接失败 对象 imp exce tac sql java res man
原文地址:https://www.cnblogs.com/borter/p/9451005.html