加载jdbc驱动程序的三种不同方式

2022-11-02 00:00:00 加载 驱动程序 三种

1.比较常用

try{
       Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动
       String url="jdbc:mysql://localhost:3306/databasename";//数据库连接子协议
       //databasename:需要连接的数据库名字;username:数据库登录用户名;password:数据库登录密码;
       Connection conn=DriverManager.getConnection(url,"root","psw");
       Statement stmt=conn.createStatement();
       ResultSet rs=stmt.executeQuery("select * from tablename");
       while(rs.next()){//不断指向下一条记录
            System.out.println("DeptNo:"+rs.getInt(1));
            System.out.println("\tDeptName:"+rs.getString(2));
            System.out.println("\tLOC:"+rs.getString(3));
}         
    rs.close();
    stmt.close();
    conn.close();
}catch(ClassNotFoundException e){
   System.out.println("找不到指定的驱动程序类!");
}catch(SQLException e){
    e.printStackTrace();
}

2.通过系统的属性设置

try{
       System.setProperty("jdbc.driver","com.mysql.jdbc.Driver");
        //系统属性指定数据库驱动
    //数据库连接子协议
       Connection conn=DriverManager.getConnection(url,"root","psw");
       Statement stmt=conn.createStatement();
       ResultSet rs=stmt.executeQuery("select * from tablename");
       while(rs.next()){//不断指向下一条记录
            System.out.println("DeptNo:"+rs.getInt(1));
            System.out.println("\tDeptName:"+rs.getString(2));
            System.out.println("\tLOC:"+rs.getString(3));
}         
    rs.close();
    stmt.close();
    conn.close();
}catch(SQLException e){
    e.printStackTrace();
}

3、注册相应的db的jdbc驱动,在编译时需要导入对应的lib

try{
       new com.mysql.jdbc.Driver();//创建driver对象,加载数据库驱动
       String url="jdbc:mysql://localhost:3306/databasename";
       //数据库连接子协议
       Connection conn=DriverManager.getConnection(url,"root","psw");
       Statement stmt=conn.createStatement();
       ResultSet rs=stmt.executeQuery("select * from tablename");
       while(rs.next()){//不断指向下一条记录
            System.out.println("DeptNo:"+rs.getInt(1));
            System.out.println("\tDeptName:"+rs.getString(2));
            System.out.println("\tLOC:"+rs.getString(3));
}         
    rs.close();
    stmt.close();
    conn.close();
}catch(SQLException e){
    e.printStackTrace();
}

注意:
在使用Connection的时候,JSP中出现:Connection cannot be resolved to a type的报错,这是由于没有导入Connect这个类。
在jsp的开始导入jar:

<%@page import="java.sql.*" %>
<%@ page language="java" import="java.sql.*" pageEncoding="UTF-8"%>
    原文作者:cao_yanjie
    原文地址: https://blog.csdn.net/cao_yanjie/article/details/78063013
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章