java: MS Sql Server Connection

 

/*
 * 版權所有 2021 塗聚文有限公司
 * 許可信息查看:
 * 描述:
 *
 * 歷史版本: JDK 14.02
 * 2021-12-12 創建者 geovindu
 * 2021-12-15 添加 Lambda
 * 2021-12-15 修改:date
 * 接口類 mssql-jdbc-9.4.1.jre16.jar.
 * 數據庫:MSSQL Server 2019
 * 2021-12-15 修改者:Geovin Du
 * 生成API幫助文檔的指令:
 *javadoc - -encoding Utf-8 -d apidoc DuMsSQLConn.java
 *https://www.microsoft.com/en-us/software-download/windows10
 *https://github.com/PaddlePaddle/PaddleOCR
 *https://docs.microsoft.com/es-es/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver15
 *https://github.com/microsoft/mssql-jdbc/blob/main/README.md

 * */



import java.sql.*;
import com.microsoft.*;





public class DuMsSQLConn {
	
	Connection con;
	Statement stmt = null;
	//
	public Connection getConnection() 
	{
		
		  //數據庫地址
		  String url = "jdbc:sqlserver://GEOVINDU;DataBaseName=geovindu";  //GEOVINDU  //localhost
		  //
	      String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  //com.mysql.cj.jdbc.Driver  //com.mysql.jdbc.Driver
	      //
	      String userName = "sa";
	      //
	      String password = "7塗聚文";

	      try {
	          Class.forName(driverName);
	          System.out.println("Ms SQL 數據庫驅動加載成功");
	      } catch 
	      (ClassNotFoundException e) 
	      {
	          e.printStackTrace();
	      }
	      
	      try 
	      {
	          con = DriverManager.getConnection(url,userName,password);
	          System.out.println("Ms SQL數據庫連接成功"); 
	          System.out.println(" 實例化Statement對象...");       // 執行查詢
	          stmt = con.createStatement();
	          String sql;
	          sql = "SELECT RoleType,RoleTypeName,RoleTypeDescribe  FROM RoleTypeList";
	          ResultSet rs = stmt.executeQuery(sql);
	      
	          // 展開結果集數據庫
	          while(rs.next()){
	              // 通過字段檢索
	              int typid  = rs.getInt("RoleType");
	              String rolename = rs.getString("RoleTypeName");
	              String roledec = rs.getString("RoleTypeDescribe");
	  
	              // 輸出數據
	              System.out.print("角色ID: " + typid);
	              System.out.print("  ,  角色名字: " + rolename);
	              System.out.print("  , 角色描述: " + roledec);
	              System.out.print("\n");
	          }
	          // 完成後關閉
	          rs.close();
	          stmt.close();
	          con.close();
	          
	          
	          
	      }
	      catch (SQLException e) 
	      {
	          e.printStackTrace();
	      }
		 return con;
	
	}
	

}
	
	
	

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章