JAVA连接SQL Server 2012脚本

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

public class DButil {
 
 // 连接驱动 
 private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
 // 连接路径  zzd数据库名
 private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=zzd";   
 // 登录用户名 
 private static final String USERNAME = "sa"; 
 // 登录密码 
 private static final String PASSWORD = "123456"; 
  
 //静态代码块 
 static { 
  try { 
   // 加载驱动 
   Class.forName(DRIVER); 
  } catch (ClassNotFoundException e) { 
   e.printStackTrace();
   System.out.println("数据库连接异常");
  } 
 } 
 
 /* 
  * 获取数据库连接 
  */ 
 public static Connection getConn() { 
  Connection conn = null; 
  try{ 
   conn=DriverManager.getConnection(URL, USERNAME, PASSWORD); 
  }catch(SQLException e){ 
   e.printStackTrace(); 
  } 
  return conn; 
 } 
 
 /* 
  * 关闭数据库连接,注意关闭的顺序 
  */ 
 public void close(ResultSet rs, PreparedStatement ps, Connection conn) { 
  if(rs!=null){ 
   try{ 
    rs.close(); 
    rs=null; 
   }catch(SQLException e){ 
    e.printStackTrace(); 
   } 
  } 
  if(ps!=null){ 
   try{ 
    ps.close(); 
    ps=null; 
   }catch(SQLException e){ 
    e.printStackTrace(); 
   } 
  } 
  if(conn!=null){ 
   try{ 
    conn.close(); 
    conn=null; 
   }catch(SQLException e){ 
    e.printStackTrace(); 
   } 
  } 
 } 
}

 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class test {

	public static void main(String[] args) {
		Connection conn=null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		DButil t = new DButil();
		try {
			String sql = "select * from Class";
			conn = t.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				int CNo = rs.getInt("CNo");  //列名
				String Depar = rs.getString("Depar");
				String Speciality = rs.getString("Speciality");
				
				System.out.println(CNo+"-"+Depar+"-"+Speciality);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			t.close(rs, ps, conn);
		}
	}
}

JAVA连接SQL Server 2012脚本_第1张图片

你可能感兴趣的:(JAVA连接SQL Server 2012脚本)