JDBC技术

一、JDBC

1、jdbc

sun公司设计的一套调用java语言操作不同数据库的接口

2、使用jdbc发送sql前提

(1)数据库的ip地址
(2)端口
(3)数据库用户名
(4)密码

3、连接数据库

第一种方式:
(1)创建一个驱动程序对象
Driver driver = new com.mysql.jdbc.Driver();
(2)设置用户名的密码
使用Property对象的setProperty方法
Properties property = new Properties();
property.setProperty(“user”, user);
property.setProperty(“psw”, psw);
(3)连接。
driver.connect(url, property); //url遵循jdbc协议
格式:jdbc:子协议://主机ip:端口号/数据库(mysql一般为3306,主机ip端口号一般可省略)
第二种方式:
(1)通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
Class.forName(“com.mysql.jdbc.Driver”);
(2)连接
Connection conn = DriverManager.getConnection(url,user,psw);

4、主要API

(1)接口和方法

|- Driver接口: 表示java驱动程序接口。所有的具体的数据库厂商要来实现此接口。
|- connect(url, properties): 连接数据库的方法。
url: 连接数据库的URL
URL语法: jdbc协议:数据库子协议://主机:端口/数据库
user: 数据库的用户名
password: 数据库用户密码
|- DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序
|-registerDriver(driver) : 注册驱动类对象
|-Connection getConnection(url,user,password); 获取连接对象

|- Connection接口: 表示java程序和数据库的连接对象。
|- Statement createStatement() : 创建Statement对象
|- PreparedStatement prepareStatement(String sql) 创建PreparedStatement对象
|- CallableStatement prepareCall(String sql) 创建CallableStatement对象

|- Statement接口: 用于执行静态的sql语句
|- int executeUpdate(String sql) : 执行静态的更新sql语句(DDL,DML)
|- ResultSet executeQuery(String sql) :执行的静态的查询sql语句(DQL)

|-PreparedStatement接口:用于执行预编译sql语句
|- int executeUpdate() : 执行预编译的更新sql语句(DDL,DML)
|-ResultSet executeQuery() : 执行预编译的查询sql语句(DQL)

|-CallableStatement接口:用于执行存储过程的sql语句(call xxx)
|-ResultSet executeQuery() : 调用存储过程的方法

|- ResultSet接口:用于封装查询出来的数据
|- boolean next() : 将光标移动到下一行
|-getXX() : 获取列的值

(2)比较PreparedStatement vs Statment

1)语法不同:PreparedStatement可以使用预编译的sql,而Statment只能使用静态的sql
2)效率不同: PreparedStatement可以使用sql缓存区,效率比Statment高

(3)Statement的注入问题

1=1 表示恒成立; – 表示注释sql
SELECT *FROM users WHERE username=’liming’ OR 1=1 – and passward=’123456’
如果使用Statement静态sql,name设置为private String name = “liming’ OR 1=1 – “;
此时的密码被注释,将会查询到所有记录。

5、使用jdbc

package com.wk.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;

import org.junit.Test;

/*
 * 
 * 测试连接mysql数据库的方法
 */

public class JDBC1 {

    private String user = "wk";
    private String psw = "199645";

    //连接数据库的url
    private String url = "jdbc:mysql://localhost:3306/test";

    @Test
    public void test() throws Exception{

        //1、创建驱动程序
        Driver driver = new com.mysql.jdbc.Driver();

        //2、设置用户名和密码

        Properties property = new Properties();
        property.setProperty("user", user);
        property.setProperty("psw", psw);

        //3、连接数据库

        Connection conn = driver.connect(url, property);
        System.out.println("test1连接");
        System.out.println(conn);
    }

    @Test
    public void test2() throws Exception{
        Driver driver = new com.mysql.jdbc.Driver();

        //使用DriverManager管理驱动
        //1、注册
        DriverManager.registerDriver(driver);

        //2、连接
        Connection conn = DriverManager.getConnection(url,user,psw);
        System.out.println("test2连接");
        System.out.println(conn);

    }

    @Test
    public void test3() throws Exception{

        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection(url,user,psw);
        System.out.println("test3连接");
        System.out.println(conn);
    }
}

打印结果

test1连接
com.mysql.jdbc.JDBC4Connection@72e6f7d2
test2连接
com.mysql.jdbc.JDBC4Connection@58d9660d
test3连接
com.mysql.jdbc.JDBC4Connection@5e785d65

6、自定义JdbcUtil工具类

第一种方法:直接在代码中给出要连接的数据库

package com.wk.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 1. 返回连接 
 * 2. 关闭
 * 
 * @author wk
 * 
 */
public class JdbcUtil {

    // 连接参数
    // private String url = "jdbc:mysql://localhost:3306/myfirst";
    private static String url = "jdbc:mysql:///myfirst";
    private static String user = "wk";
    private static String password = "199645";

    /**
     * 返回连接对象
     */
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭
     */
    public static void close(Connection con, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();   
                rs = null;   // 回收资源
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
            if (con != null && !con.isClosed()) {
                con.close();
                con = null;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

第二种方法:在配置文件中配置用户名、密码、数据库等参数

package com.wk.jdbc_util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/*
 * 
 * JDBC连接工具类
 * 
 */
public class JdbcUtil {

    private static String user = null;
    private static String password = null;

    //连接数据库的url
    private static String url = null;
    private static String driverClass = null;

    //静态代码块加载注册驱动程序
    static{
        try {

            //使用Propertise对象
            Properties p = new Properties();
//          FileInputStream in = new FileInputStream("./src/db.properties");

            /*
             * 使用类路径的读取方式
             * 
             *  /  表示classpath的根目录
             *  
             *  java项目中,classpath的根目录从bin开始
             *  在web项目中,classpath的根目录从WEB-INF/classes目录开始
             * 
             */
            InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
            p.load(in);

            user = p.getProperty("user");
            password = p.getProperty("password");
            url = p.getProperty("url");
            driverClass = p.getProperty("driverClass");

            /*System.out.println(user);
            System.out.println(password);
            System.out.println(url);
            System.out.println(driverClass);*/

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public static Connection getConnection(){
        try {
            Connection conn = DriverManager.getConnection(url,user,password);
            return conn;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    /**
     * 
     * @param conn  Connection对象
     * @param state Statement对象
     */
    public static void close(Connection conn,Statement state){

        if(state!=null)
            try {
                state.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new RuntimeException();
            }
        if(conn!=null)
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new RuntimeException();
        }
    }

    /**
     * 
     * @param conn    Connection对象
     * @param state   Statement对象
     * @param rSet    ResultSet对象
     */
    public static void close(Connection conn,Statement state,ResultSet rSet){
        if(rSet!=null)
            try {
                rSet.close();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        if(state!=null)
            try {
                state.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new RuntimeException();
            }
        if(conn!=null)
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new RuntimeException();
            }
    }

}

db.properties文件内容:

user=wk
password=199645
url=jdbc:mysql://localhost:3306/myfirst
driverClass=com.mysql.jdbc.Driver

第三种方法:使用CP03连接池,首先导入依赖库c3p0-0.9.1.2.jar,然后配置c3p0.xml文件



jdbc:mysql:///myfirst
com.mysql.jdbc.Driver
wk
199645
3
6
3000


package com.wk.utils;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtil {

    //初始化连接池

    private static DataSource dataSource;


    static{
        dataSource = new ComboPooledDataSource();
    }

    //获取连接
    public static QueryRunner getQueryRunner(){
        return new QueryRunner(dataSource);
    }

    public static DataSource getDataSource() {
        return dataSource;
    }
}

注意:使用JDBC时一定要开启mysql服务!!!

你可能感兴趣的:(Java,数据库)