数据库连接

来源:互联网 发布:雅马哈 电钢琴 知乎 编辑:程序博客网 时间:2024/06/06 10:22

1.第一种方式 

 //加载驱动      Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");    //获取连接      cn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=...","username","password");

 

2.配置好数据源

       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");       cn=DriverManager.getConnection("jdbc:odbc:check");


3.数据库连接池

在Tomcat的context.xml中配置如下代码:

<Context reloadable="true">        <WatchedResource>WEB-INF/web.xml</WatchedResource>             <Resource name="sample" auth="Container"type="javax.sql.DataSource" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" maxIdle="10" maxWait="5000" url="jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=数据库名" username="sa" password="123456" maxActive="100" />  </Context>


然后在webapp中的web.xml中配置如下:

  <resource-ref>           <description>DB Connection</description>     <res-ref-name>sample</res-ref-name>           <res-type>javax.sql.DataSource</res-type>           <res-auth>Container</res-auth>        </resource-ref> 

 

最后连接数据库代码:

        Context ctx=new InitialContext();        DataSource sp=(DataSource)ctx.lookup("java:comp/env/sample");        cn=sp.getConnection();        ctx.close();   




 

原创粉丝点击