快捷搜索: 王者荣耀 脱发

JDBC入门级教程——应用篇(二)

本篇主要展示数据库连接后的简单操作应用示例。

public Connection getConnection() throws ClassNotFoundException, SQLException {
//        获取数据库连接对象,方便其他类中调用。 故采用Connection类型返回值
        Class.forName(driver_mysql);
        return DriverManager.getConnection(url,username_mysql,password_mysql);
//        返回Connection对象
    }

数据库应用完整代码:

package ;

import java.sql.*;

public class Tool {
//    数据库操作工具类
    public static void main (String [] args) throws SQLException, ClassNotFoundException {
        JDBC test2=new JDBC();
        test2.Connect_mysql();
//        进行数据库连接  同包下的共享
        Connection connection=test2.getConnection();
//        获取数据库连接对象 connection
        Tool do_sql=new Tool();
//        实例化本类对象  调用不同工具
        do_sql.add(connection);
//        数据增加操作
        do_sql.show(connection);
//        数据查询操作

    }
    Statement statement=null;
    public void show(Connection connection) throws SQLException {
//        数据查询
        String sql="select * from table ";
//        table放置欲连接数据表名称
//        SQL语句
        statement=connection.createStatement();
//        Statement 对象用 Connection 的方法createStatement 创建,用于执行数据库操作语句
        ResultSet resultSet=null;
//        创造结果集对象
        resultSet=statement.executeQuery(sql);
//        执行SQL语句
        while(resultSet.next()){
//            进行控制台数据展示
            System.out.println("字段1:"+resultSet.getString("name")+"  字段2:"+resultSet.getString("name")+"  字段三:"
                    +resultSet.getString("name")+"  字段4:"+resultSet.getString("name"));
//            getString内放置数据表中字段名称  根据自身开发灵活应用
        }
    }

    public void add(Connection connection) throws SQLException {
//        数据增加
        String sql="insert into peolple_info (name,phone,password,email)" +
                "value (?,?,?,?)";
//        为避免冗杂,采用占位符SQL语句
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
//        PreparedStatement是Statement的子接口  可以传入带占位符的SQL语句
        preparedStatement.setString(1,"aa");
        preparedStatement.setString(2,"aa");
        preparedStatement.setString(3,"aa");
        preparedStatement.setString(4,"aa");
//        ""中填写需要改变的值,根据需要可以以参数形式放入,或利用java bean组件操作
//        此处不做样例
        preparedStatement.executeUpdate();
//        executeUpdate 的返回值是一个整数,指示受影响的行数
    }

}

本篇代码主要涉及数据库连接后,对数据的读取和写入操作,为基本语法,可以根据自身情况,编写适合自己的封装方法,工程构造。熟悉使用SQL语句,熟悉应用各种语言接口。

经验分享 程序员 微信小程序 职场和发展