Java操作数据库指南(之一)

Posted 大码王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java操作数据库指南(之一)相关的知识,希望对你有一定的参考价值。

一、java实现关系型数据库操作

1、java操作mysql增删改查

1、帮助类

package com.gr.DBHerpel;

import java.sql.*; //导包

/** 
 * ClassName: DBHerpel
 * @Description: TODO 数据库辅助类
 * @author 情绪i
 */
public class DBHerpel {

    private static Connection Conn; // 数据库连接对象

    // 数据库连接地址
    private static String URL = "jdbc:mysql://localhost:3306/myschool?characterEncoding=utf8&useSSL=true";

    // 数据库的用户名
    private static String UserName = "root";
    // 数据库的密码
    private static String Password = "1234";

    /**
     * * @Description: TODO 获取访问数据库的Connection对象
     * @param @return
     * @return Connection 连接数据的对象
     * @author 情绪i
     */
    public static Connection getConnection() {

        try {

            Class.forName("com.mysql.jdbc.Driver"); // 加载驱动

            System.out.println("加载驱动成功!!!");
        } catch (ClassNotFoundException e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        try {

            //通过DriverManager类的getConenction方法指定三个参数,连接数据库
            Conn = DriverManager.getConnection(URL, UserName, Password);
            System.out.println("连接数据库成功!!!");

            //返回连接对象
            return Conn;

        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }

}

2、增删改查

package com.gr.visitServer;

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

import com.gr.DBHerpel.DBHerpel;

public class VisitMySql {

    // 连接对象
    private Connection conn;
    // 传递sql语句
    private Statement stt;
    // 结果集
    private ResultSet set;

    // 1、查询
    public void Select() {
        try {
            // 获取连接
            conn = DBHerpel.getConnection();
            if (conn == null)
                return;
            // 定义sql语句
            String Sql = "select * from login";
            // 执行sql语句
            stt = conn.createStatement();
            // 返回结果集
            set = stt.executeQuery(Sql);
            // 获取数据
            while (set.next()) {

                System.out.println("用户名:" + set.getString(1) + "\\t密码:"
                        + set.getString(2));

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            // 释放资源
            try {
                set.close();
                conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }

        }
    }
    //2、增
    // 使用Statement接口的executeUpdate()方法向数据库添加数据
    public void Add(){
        
        try {
            //获取连接
            conn = DBHerpel.getConnection();
            if(conn==null)
            return;
            //获取用户输入的账号和密码
            Scanner input = new Scanner(System.in);
            System.out.print("请输入用户名:");
            int user = input.nextInt();
            System.out.print("请输入密码:");
            String pwd = input.next();
            //定义sql语句
            String sql = "insert into login values("+user+" , \'"+pwd+"\');";
            //获取Statement对象
            stt = conn.createStatement();
            //执行sql语句
            stt.executeUpdate(sql);
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //释放资源
            try {
                
                conn.close();
                
            } catch (Exception e2) {}
            
        }
    }
    //3、删
    //使用Statement接口的executeUpdate()方法实现从数据库删除数据
    public void Delete(){
        try {
            
            //获取连接
            conn = DBHerpel.getConnection();
            if(conn==null)
            return;
            
            //提示用户输入要删除的用户
            System.out.print("请输入删除的用户:");
            Scanner input = new Scanner(System.in);
            int user = input.nextInt();
            
            //定义sql语句
            String deleteSql = "DELETE FROM login WHERE user="+user+";";
            //获取Statement对象
            stt = conn.createStatement();
            //执行sql语句
            stt.executeUpdate(deleteSql);
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //释放资源
            try {
                conn.close();
                
            } catch (Exception e2) {}
            
        }
    }
    //4、改
    //使用PreparedStatement接口中的executeUpdate()方法实现修改数据
    public void Update(){
        
        try {
            //获取连接
            conn = DBHerpel.getConnection();
            if(conn==null)
                return;
            
            //用户输入要修改的账户
            System.out.print("请输入用户名:");
            Scanner input = new Scanner(System.in);
            int user = input.nextInt();       //提示用户输入新的密码
            System.out.print("请输入新的密码:");
            String NewPwd = input.next();
            //定义Sql语句
            String UpdateSql = "UPDATE login SET pwd = \'"+NewPwd+"\' WHERE user = "+user+";";
            //创建Statement对象
            PreparedStatement ps = conn.prepareStatement(UpdateSql);
            //执行sql语句
            ps.executeUpdate();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }finally{
            //释放资源
            try {
                conn.close();
            } catch (Exception e2) {}
            
        }
    }
}

3、测试

package com.gr.Test;
import com.gr.visitServer.VisitMySql;
public class Test {
    public static void main(String[] args)
        //实例化对象
        VisitMySql vs = new VisitMySql();
       //调用查询方法
        vs.Select();   
    }

}

2、java操作oracle增删改查

1、帮助类

package oracle;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
/**
 * @description: Oracle连接工具类
 */
public class DBUtil {
    //数据库连接地址
    private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
    //用户名
    private static String username= "system";
    //密码
    private static String password ="ZZZ111";
    //驱动名称
    private static String jdbcName = "oracle.jdbc.OracleDriver";
 
    /*获取数据库连接 */
    public static Connection getCon(){
        try {
            Class.forName(jdbcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection con = null;
        try {
            con = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
 
    /*关闭数据库连接*/
        public static void closeCon(Connection con) throws SQLException {
            if (con != null)
                con.close();
        }
 
        public static void main(String[] args){
            try {
                getCon();
                System.out.println("数据库连接成功");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("数据库连接失败");
            }
        }
 
}

2、增删改查

package oracle;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class OracleDemo {
    //连接对象
    Connection connection=null;
    //创建预编译对象
    PreparedStatement ps=null;
    //创建结果集
    ResultSet rs = null;
 
    /*插入*/
    public int insert(){
        int result = 0;
        connection = DBUtil.getCon();
        String sql = "insert into student values(?,?,?)";
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1,2);
            ps.setString(2,"老王");
            ps.setString(3,"女");
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeCon(connection);
        }
        return result;
    }
    /*查询*/
    public void select(){
        connection = DBUtil.getCon();
        String sql = "select id,name,gender from student";
        try {
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String gender = rs.getString(3);
                System.out.println("ID:"+id + " NAME:"+name+" GENDER:"+gender);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeCon(connection);
        }
    }
    /*修改*/
    public int update(){
        connection = DBUtil.getCon();
        String sql = "update student set name = ?,gender = ? where id = ?";
        int result = 0;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,"老张");
            ps.setString(2,"男");
            ps.setInt(3,2);
           result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
           }finally {
            DBUtil.closeCon(connection);
        }
 
        return result;
 
    }
 
    /*删除 */
    public int delete(){
        int result = 0;
        connection = DBUtil.getCon();
        String sql = "delete from student where id = ?";
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1,1);
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeCon(connection);
        }
        return result;
    }
 
    public static void main(String[] args){
        OracleDemo od = new OracleDemo();
        /*int add = od.add();
        System.out.println(add);*/
        od.select();
//        System.out.println(od.delete());
    }
}

 

以上是关于Java操作数据库指南(之一)的主要内容,如果未能解决你的问题,请参考以下文章

如何在片段中填充列表视图?

JAVA进阶架构师指南之一:如何进行架构设计

3. 编程规范和编程安全指南--java

Vue3官网-高级指南(十七)响应式计算`computed`和侦听`watchEffect`(onTrackonTriggeronInvalidate副作用的刷新时机`watch` pre)(代码片段

Java代码签名证书申请和使用指南

Java语言基础之方法的设计