java当中JDBC当中JNDI用来查找dataSource的例子
JNDI用来查找dataSource的例子:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
import javax.naming.InitialContext;
import javax.naming.Context;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.util.Properties;
import net.sourceforge.jtds.jdbcx.*;
public class ClassPut {
public static void main(String a[]) {
try {
/* JtdsDataSource dataSource=new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("NorthWind");
dataSource.setUser("sa");
dataSource.setPassword("1234");
*/
MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
ds.setURL("jdbc:mysql://localhost:3306/test");
ds.setUser("root");
ds.setPassword("1234");
Properties prop = new Properties();
prop.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
Context ctx=new InitialContext(prop);
/*here the following statement writes a file .bindings under the f Disk. because this project is under the f disk.*/
ctx.rebind("abc",ds);
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面的程序只是存入硬盘,想查找出来得用下面的程序:
import javax.naming.InitialContext;
import javax.naming.Context;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import net.sourceforge.jtds.jdbcx.*;
public class ClassGet {
public static void main(String a[]) {
try {
Properties prop = new Properties();
prop.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
Context ctx=new InitialContext(prop);
/*it will lookup things under the f disk---.bindings file, lookup will directly instantiate
an object of net.sourceforge.jtds.jdbcx.JtdsDataSource in memory. */
Object obj=ctx.lookup("abc");
System.out.println(obj);
MysqlConnectionPoolDataSource ds = (MysqlConnectionPoolDataSource)obj;
Connection con = ds.getConnection();
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select count(*) from books");
if(rs.next())
System.out.println("There are " + rs.getInt(1)
+ " records in books table.");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
9.sqlserver2008's problem:
1)java连接sql server 2008遇到的问题之一:
使用 sql server 2008 时,无法使用SA用户登陆(应该是所有sql server版本都会出现这样的问题)
解决方法:
1、打Microsoft Sql Server Management Studio,以windows验证方式登陆,打开服务器属性窗口(在数据库服务器图标上点右键选"属性"(right click the server name,choose property)),选择"安全性"选项,
2、服务器验证方式选择SQL SERVERTT和windows验证方式,确认
3、然后再到"安全性-登陆名"处设置SA用户属性,
4、设置密码
5、状态-启用SA用户
做完这五个操作后,we can now login as "sa" in Sql Server Management Studio.
2) sqlserver2008默认情况下是禁用了tcp/ip连接。启动tcp/ip连接的方法,
开始 \Microsoft SQL Server 2008\配置工具\目录下的SQL Server Configuration Manager,选择\sqlserver network configuration\mssqlserver协议,
然后右边窗口有个tcp/ip协议,然后启动它,在启动TCP/IP协议后还要把其属性
中的TCP端口号改为1433,,把sqlserver