initializejndi.java

来自「本套光盘提供了本书各章实例的所需的部分源程序文件以及数据库文件。读者 需要使用」· Java 代码 · 共 48 行

JAVA
48
字号
// We need to import the actual DataSource implementation 
import com.inet.tds.TdsDataSource;
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;
import java.sql.* ;
import javax.sql.* ;

public class InitializeJNDI {
// First we define the relevant parameters for this datasource
private String serverName = "localhos";
private int portNumber = 1433;
private String login = "javadb";
private String password = "javadb";
private String databaseName = "Northwind";

/*This is the name we will assign to our datasource. Because we are using the file system provider, our name follows the file system naming rules. The JNDI reserved subcontext for JDBC applications is jdbc, thus our name starts appropriately.*/
private String filePath = "ProgramFiles/Javadb";
public InitializeJNDI() {
// To pass in the necessary parameters, we need to create and then populate a Hashtable.
Hashtable env = new Hashtable();
 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
try {
// Create the initial context
   Context ctx = new InitialContext(env);
// Here we create the actual DataSource and then set the relevant // parameters.
    TdsDataSource ds = new TdsDataSource();

 		ds.setServerName(serverName);
        ds.setPortNumber(portNumber);
        ds.setDatabaseName(databaseName);
        ds.setUser(login);
        ds.setPassword(password);
        ds.setDescription("JDBC DataSource Connection");
// Now we bind the DataSource object to the name we selected earlier.
       ctx.bind(filePath, ds);
       ctx.close();
// Generic Exception handler, in practice, this would be replaced by an 
// appropriate Exception handling hierarchy.
   } catch (Exception ex) {
            System.err.println("ERROR: " + ex.getMessage());
        }
    }
    public static void main(String args[]) {
        new InitializeJNDI();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?