【Java】JDBC模糊查询及增删改小栗子

  • Post author:
  • Post category:java




模糊查询

package com.sj.www;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;
import java.util.Scanner;

public class SQLconnectiontest010 {
    public static void main(String[] args) throws Exception {
        //----获取静态文件属性的另外一种方法
        //注意文件名不带后缀
        ResourceBundle properties = ResourceBundle.getBundle("sql");
        String url = properties.getString("url");
        String user = properties.getString("user");
        String password = properties.getString("password");
        String driver = properties.getString("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.print("请输入你要查询的姓名(模糊查询):");
        Scanner scanner = new Scanner(System.in);
        String name = "_"+scanner.next()+"%";// 下划线表示任意一个字符%表示任意多个字符可以是0个也可以多个
        String sql="select ename  from emp where ename like ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,name);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println("姓名:"+resultSet.getString("ename"));
        }
        DBUtil.close(connection,resultSet,preparedStatement);
    }
}




增加一条数据

Statement statement = connection.createStatement();
        String sql="insert into emp(empno,ename,job) values(7370,'张三','打扫卫生')";
        int rows = statement.executeUpdate(sql);
        System.out.println(rows > 0 ? "加入成功!":"加入失败!");
        statement.close();
        connection.close();

在这里插入图片描述



修改一条数据

Statement statement = connection.createStatement();
        String sql="update emp set job = '吃饭' where empno=7370";
        int rows = statement.executeUpdate(sql);
        System.out.println(rows > 0 ? "修改成功!":"修改失败!");
        statement.close();
        connection.close();

在这里插入图片描述



删除一条数据

Statement statement = connection.createStatement();
        String sql="delete from emp where ename = '张三'";
        int rows = statement.executeUpdate(sql);
        System.out.println(rows > 0 ? "删除成功!":"删除失败!");
        statement.close();
        connection.close();

在这里插入图片描述


总结:增删改,格式一样,唯一不同的就是SQL语句,死记硬背也得记下来



版权声明:本文为weixin_45748004原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。