zoukankan      html  css  js  c++  java
  • java连接MySQL数据库的方式

    Java连接数据库的几种方法

    *说明

         1.以MySQL数据库为例

       2.分为四个步骤:

        建立数据库连接,

        向数据库中提交sql

        处理数据库返回的结果

        关闭数据库连接

    一:JDBC

    1.建立数据库连接

             只需要两步,注册数据库的驱动程序,然后创建数据库连接

             示例代码:   

       
      String url="jdbc:mysql://localhost:3306/test";
    
                       String Driver="com.mysql.jdbc.Driver";
    
                       String username="root";
    
                       String password="123456";
    
     
    
                       Class.forName(Driver);
    
                       Connection conn=DriverManager.getConnection(url,username,password);
    方法一

      

       
     String url="jdbc:mysql://localhost:3306/test";
    
                       String username="root";
    
                       String password="123456";
    
     
    
                       new com.mysql.jdbc.Driver();
    
                       Connection conn=DriverManager.getConnection(url,username,password);
    方法二

             首先通过java.lang.Class类的forName()静态方法动态加载MySQL驱动程序的类,这个类会自动在DriverManager中进行注册,然后通过DriverManager获得Connection类型的对象

    2.通过数据库连接池,效率高

             原理就是通过修改Tomcat服务器conf目录下的context.xml文件来进行配置的

             配置的代码:     

      
     <Context reloadable="true">
    
     
    
        <!-- Default set of monitored resources -->
    
        <WatchedResource>WEB-INF/web.xml</WatchedResource>
    
     
    
        <Resource name="jdbc/mysql" auto="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="123456" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"/>
    
     
    
        <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    
        <!--
    
        <Manager pathname="" />
    
        -->
    
     
    
        <!-- Uncomment this to enable Comet connection tacking (provides events
    
             on session expiration as well as webapp lifecycle) -->
    
        <!--
    
        <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    
        -->
    
     
    
    </Context>
    context.xml

      通过数据源对象获取连接池中的数据库连接对象

      
    Context context=new InitialContext();
    
    DataSource ds=(DataSource) context.lookup("java:/comp/env/jdbc/mysql");
    
    Connection conn=ds.getConnection();
    View Code

    3.其他步骤在后面讲

    二.以后补充

             

  • 相关阅读:
    浅析Java中的final关键字
    Eclipse导入到web项目没有run on server
    解决web项目无法部署到eclipse配置的本地tomcat
    Eclipse 导入外部项目无法识别为web项目并且无法在部署到tomcat下
    JAVA – 虚函数、抽象函数、抽象类、接口
    jsp分页
    连接数据库查询数据
    (转)解决emacs中切换输入法冲突
    sqoop的使用
    hive的使用03
  • 原文地址:https://www.cnblogs.com/aihuadung/p/8639852.html
Copyright © 2011-2022 走看看