jdbc如何连接数据库?(附代码)

jdbc如何连接数据库?(附代码)

本篇文章给大家带来的内容是jdbc如何连接数据库?(附代码),有一定的参考价值jdbc如何连接数据库?(附代码),有需要的朋友可以参考一下,希望对你有所帮助。

JDBC简介

JDBC全称为:Java Data Base (java数据库连接),可以为多种数据库提供填统一的访问。JDBC是sun开发的一套数据库访问编程接口,是一种SQL级的API。它是由java语言编写完成,所以具有很好的跨平台特性jdbc连接oracle 写法,使用JDBC编写的数据库应用程序可以在任何支持java的平台上运行,而不必在不同的平台上编写不同的应用程序。【视频教程推荐:Java教程】

JDBC编程步骤

(1)加载驱动程序:

下载驱动包 :

解压jdbc连接oracle 写法,得到 jar文件。将该文件复制到Java工程目录Java // 下jdbc如何连接数据库?(附代码),→ 。

(2)获得数据库连接

(3)创建对象:

(4)向数据库发送SQL命令

(5)处理数据库的返回结果(类)

package com.baidu.emp.jdbcTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
/**
 * 开始使用jdbc连接数据库
 * @author Admin
 *
 */
public class Test001 {
    public static void main(String[] args) throws Exception {
        /**
         * 加载驱动
         */
        // 方法一:
        /*
         * import java.sql.DriverManager; import com.mysql.jdbc.Driver;
         */
        // Driver driver = new Driver();
        // DriverManager.registerDriver(driver);
        // 方法二:(推荐使用)
        Class.forName("com.mysql.jdbc.Driver");
        /**
         * 创建链接
         */
        String url = "jdbc:mysql://localhost:3306/testjdbc";
        String user = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, user, password);
        // 创建statement对象
        Statement statement = connection.createStatement();
        /**
         * 执行SQL,获取结果集
         */
        String sql = "select * from test01";
        ResultSet result = statement.executeQuery(sql);
        // 遍历结果集
        while (result.next()) {
            String name = result.getString("name");
            int id = result.getInt("id");
            System.out.println(name + "t" + id);
        }
        /**
         * 关闭链接,释放资源
         */
        result.close();
        statement.close();
        connection.close();
    }
}

防止SQL注入改用

package com.boya.emp.jdbcTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
 * SQL注入,使用prepareStatement对象进行预编译
 * @author Admin
 *
 */
public class Test002 {
    public static void main(String[] args) throws Exception {
        /**
         * 加载驱动
         */
        Class.forName("com.mysql.jdbc.Driver");
        /**
         * 创建链接
         */
        String url = "jdbc:mysql://localhost:3306/testjdbc";
        String user = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, user, password);
        // 写SQL 
        String sql = "select * from test01 where id = ?";
        //创建statement对象,预编译
        PreparedStatement statement = connection.prepareStatement(sql);
        //设置参数
        statement.setInt(1, 2);
        /**
         * 执行SQL,获取结果集
         */
        ResultSet result = statement.executeQuery();
        // 遍历结果集
        while (result.next()) {
            String name = result.getString("name");
            int id = result.getInt("id");
            System.out.println(name + "t" + id);
        }
        /**
         * 关闭链接,释放资源
         */

jdbc连接oracle 写法

result.close(); statement.close(); connection.close(); } }

进行代码优化,设置配置文件,工具类jdbc连接oracle 写法,实现增删该查

增加配置文件方便修改数据库,用户登录。。。

jdbc.(配置文件名)

driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testjdbc
userName=root
password=root

注意写配置文件时中间不可以有空格,引号之类的

工具类:增强了代码的复用性

package com.baidu.emp.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class JdbcUtils {
    static String driverClassName;
    static String url;
    static String user;
    static String password;
    static {
        // 创建配置文件对象
        Properties properties = new Properties();
        // 加载配置文件输入流
        InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        // 重新加载配置文件
        try {
            properties.load(inputStream);
            // 获取配置文件的值
            driverClassName = properties.getProperty("driverName");
            url = properties.getProperty("url");
            user = properties.getProperty("userName");
            password = properties.getProperty("password");
            Class.forName(driverClassName);
        } catch (Exception e) {
            // 抛出异常
            throw new RuntimeException(e);
        }
    }
    /**
     * 获取连接
     */
    @Test
    public void testName() throws Exception {
        
        System.out.println(driverClassName);
    }
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            // 抛出异常
            throw new RuntimeException(e);
        }
        return connection;
    }
    /**
     * 关闭链接,释放资源
     */
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            resultSet = null; // 垃圾及时清除
            //注意,不要弄成死循环
            close(connection, statement);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 增删改释放资源
     */
    public static void close(Connection connection, PreparedStatement statement) {
        try {
            if (connection != null) {
                connection.close();
            }
                
            connection = null;
            if (statement != null) {
                statement.close();
            }
            statement = null;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

测试增删改查:

jdbc连接oracle 写法

package com.baidu.emp.jdbcTest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baidu.emp.utils.JdbcUtils;
/**
 * 使用jdbcUtils连接数据库进行增删改查
 * 
 * @author Admin
 *
 */
public class Test003 {
    // 初始化值
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;
    @Before
    public void start() throws Exception {
        // 创建链接
        connection = JdbcUtils.getConnection();
        System.out.println("创建链接");
    }
    @After
    public void end() throws Exception {
        // 关闭链接
        JdbcUtils.close(connection, statement, result);
        System.out.println("关闭链接");
    }
    
    /**
     *插入数据
     * @throws Exception
     */
    @Test
    public void add() throws Exception {
        String sql = "insert into test01 values(null,?)";
        statement = connection.prepareStatement(sql);
        statement.setString(1, "李四");
        int result = statement.executeUpdate();
        if (result!=0) {
            System.out.println("添加成功");
        }
    }
    /**
     * 删除数据
     * @throws Exception
     */
    @Test
    public void del() throws Exception {
        String sql = "delete from test01 where id =?";
        statement = connection.prepareStatement(sql);
        statement.setInt(1,3);
        int result = statement.executeUpdate();
        if (result!=0) {
            System.out.println("删除成功");
        }
    }
    /**
     * 修改数据
     * @throws Exception
     */
    @Test
    public void change() throws Exception {
        String sql = "update test01 set name = ? where id = ?";
        statement = connection.prepareStatement(sql);
        statement.setString(1, "张飞");
        statement.setInt(2, 2);
        int result = statement.executeUpdate();
        if (result!=0) {
            System.out.println("修改成功");
        }
    }
    
    /**
     * 查询全部数据
     * @throws Exception
     */
    @Test
    public void findAll() throws Exception {
        String sql = "select id , name from test01";
        statement = connection.prepareStatement(sql);
        result = statement.executeQuery();
        if (result.next()) {
            System.out.println("查询成功");
        }
    }
    
    /**
     * 条件查询数据
     * @throws Exception
     */
    @Test
    public void findOne() throws Exception {
        String sql = "select id , name from test01 where id = ?";
        statement = connection.prepareStatement(sql);
        statement.setInt(1, 2);
        result = statement.executeQuery();
        if (result.next()) {
            System.out.println("查询成功");
        }
    }
}

存在错误望各位同仁指出,非常感谢

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!

公告:
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299

资源库 - 资源分享下载网 » jdbc如何连接数据库?(附代码)

常见问题FAQ

关于资源售价和售后服务的说明?
本站所有资源的标价均为本站收集资源的辛苦费,不代表资源本身的价值。软件是高智慧高价值的商品,不可能是白菜价。本站资源标价只是赞助费用,收取的赞助费仅用来维持本站的日常运营!毕竟收集整理资料需要投入云计算资源和站长大量的精力。
代码有没有售后服务和技术支持?
由于代码的运行具有不可预见性,本站不保证代码完整可运行,不提供技术支持和售后服务。 本站原创代码都是站长自己开发的,可以有偿提供技术支持服务。 网站里标明【亲测】的代码都是站长亲测过的,其他的代码由于精力有限,没有一一测试,不能保证代码就一定能够使用,更没有技术支持服务,下载前请自行斟酌。
有没有搭建服务?
由于搭建服务比较费时费力,所以本站除了原创代码外均不提供搭建服务。本站分享代码纯属兴趣爱好,不以盈利为目的,请勿咨询有没有搭建服务,谢谢理解。
链接地址失效了怎么办?
请带上资源链接地址联系客服,工作时间内我们看到后将第一时间回复。
关于解压密码
本站资源一般都没有加密,如果发现需要解压密码的,那么就输入 hao.35dc.com 试试。

发表评论

资源库,由老程序员细心甄别、精心筛选,只为提供优质的源码资源

关于我们 联系我们