将sqljdbc4.jar包添加到工程

连接SqlServer 2008数据库

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class Test {

	public static void main(String[] args) {
		
	   Connection conn;
         Statement stmt;
         ResultSet rs;
         String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;";
         String sql = "select * from student";
         try {
             // 连接数据库
             conn = DriverManager.getConnection(url, "sa", "Rfid123456");
             // 建立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 name = rs.getString("name");
                 int age = rs.getInt("age");
                 System.out.println("id:" + id + "\tname:" + name + "\tage:" + age);
             }
             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("数据库连接失败");
         }

		
		
	}
	
}

 

 posted on 2017-09-04 15:38  布鲁布鲁sky  阅读(266)  评论(0编辑  收藏  举报