Java Fuzzy Query method detailed _java

Source: Internet
Author: User

When we need to develop a method to query the database, we often encounter the problem: Just do not know what the user will enter exactly what conditions, then how to deal with SQL statements to let us develop the method no matter what kind of conditions can accept the work? At this point where ' 1 ' = ' 1 ' plus list can solve the problem perfectly, less nonsense, on the code:

Fuzzy Query method public list<person> query () {list<person> List = new arraylist<> ();
    Connection con = null;
    Scanner sc = new Scanner (system.in);
    System.err.println ("Enter name:");
    String name = Sc.nextline ();
    SYSTEM.ERR.PRINTLN ("Enter ID:");
    String id = sc.nextline ();
    System.err.println ("Enter Tel:");
    String Tel = sc.nextline ();
    System.err.println ("Enter Sex:");
    String sex = Sc.nextline ();
    String sql = "Select Id,name,tel,sex from Students"//tips here, reasonably stitching strings + "where 1=1";
    List<object> List1 = new arraylist<object> ();
      Use the Commons-lang Package if (Stringutils.isnotempty (name)) {sql = "and title like?";
    List1.add ("%" + name + "%"); } if (!
      Stringutils.isempty (ID)) {sql = "and content like?";
    List1.add ("%" + ID + "%"); } if (!
      Stringutils.isempty (tel)) {sql = "and addr like?";
    List1.add ("%" + Tel + "%"); try {con = Dsutlis.getconnection ();
      After the composition of the SQL statement is complete, the PST object is generated PreparedStatement PST = con.preparestatement (SQL);
      Set the value for (int i = 0; i < list1.size (); i++) {Pst.setobject (i + 1, list.get (i));
      } ResultSet rs = Pst.executequery ();
        while (Rs.next ()) {person p = new person ();
        P.setid (rs.getstring ("id"));
        P.setname (rs.getstring ("name"));
        P.settel (Rs.getstring ("tel")); P.setsex (rs.getstring ("Sex"). Equals ("1")?
        "Male": "female");
      List.add (P);
      } rs.close ();
    Pst.close ();
    catch (Exception e) {e.printstacktrace ();
      Finally {try {con.close ();
      catch (SQLException e) {e.printstacktrace ();
  } return list;

 }

Annotations:
1. The above code operates an Oracle database:

CREATE TABLE students (
ID varchar (),
name varchar (),
tel varcher,
sex char (1),
Constraint STUD_PK primary key (ID)
);

2. Use tool class to get connection
3, Proson is a JavaBean

Here's how to use Java to do fuzzy query results

Import java.io.*;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Import javax.swing.event.*;
Import javax.swing.filechooser.*;
Import java.util.*;

 

Import java.util.regex.*; Fuzzy query public class Media {public static void main (String args[]) {JFrame frame=new mediaframe (); frame.setdefaultclose
Operation (Jframe.exit_on_close);
Frame.setvisible (TRUE); } class Mediaframe extends JFrame implements Actionlistener,listselectionlistener {private JList list; private Default
Listmodel m;
Private JButton btn;
Private JButton btn1;
Private JButton btn2;
Private JButton btn3;
Private JButton Btn4;
Private JFileChooser chooser;
Private JTextField TextField;
Map hashtable=new Hashtable ();
private int i=0;

int s=0;

Public Mediaframe () {settitle ("Media"); SetSize (600,500);
JMenuBar menu=new JMenuBar ();

Setjmenubar (menu);
JLabel label=new JLabel ("Query song Name:");
Textfield=new JTextField ();
Menu.add (label);

Menu.add (TextField);

JToolBar tb=new JToolBar (); M=new DefaultlistmodEl ();
List=new JList (m);
List.setfixedcellwidth (100);
List.setselectionmode (listselectionmodel.multiple_interval_selection);

List.addlistselectionlistener (this);

JScrollPane pane=new JScrollPane (list);

Chooser=new JFileChooser ();
Btn=new JButton ("Add song");

Btn.addactionlistener (this);
Btn1=new JButton ("delete song");

Btn1.addactionlistener (this);
Btn2=new JButton ("Empty list");

Btn2.addactionlistener (this);
Btn3=new JButton ("find track");

Btn3.addactionlistener (this);
Btn4=new JButton ("sort");

Btn4.addactionlistener (this);

JPanel panel=new JPanel ();

Panel.setlayout (New GridLayout (5,1));
Panel.add (BTN);
Panel.add (BTN1);
Panel.add (BTN2);
Panel.add (BTN3);

Panel.add (BTN4);

Tb.setlayout (new GridLayout (1,2));
Tb.add (pane);

Tb.add (panel);
Add (tb,borderlayout.west); public void actionperformed (ActionEvent event) {if (Event.getsource () ==btn) {i++; Chooser.setcurrentdirectory (New Fi

Le ("."));

int Result=chooser.showopendialog (mediaframe.this); if (result==jfilechooser.approve_option) {System.out.println (i);

String name=chooser.getselectedfile (). GetPath ();

String Str1=name;

int Str2=name.lastindexof ("//");

String name1=name.substring (Str2+1,str1.length ());

intercepts all string int str3=name1.lastindexof (".") before the Last "/";

String name2=name1.substring (0,STR3); Intercept "."

Trailing all string suffixes hashtable.put (i,name2);

M.add (0,hashtable.get (i));
System.out.println (Hashtable);
} if (Event.getsource () ==btn1) {m.removeelement () (List.getselectedvalue ());
System.out.println (m);

} if (Event.getsource () ==btn2) {System.out.println (m); i=0; Hashtable.clear (); M.clear ();}

if (Event.getsource () ==btn3) {int [] a=new int[m.getsize ()];
try {int J;

String Name=textfield.gettext ();

System.out.println (M.getsize ()); For (J=1;j<=m.getsize (); j + +) {pattern P=pattern.compile ("^" +name+ "+");//Regular expression Select all query results led by the word you fill Matcher match=

P.matcher ((String) Hashtable.get (j));

 

if (Match.find ()) {s++;
Record index node into array a[] a[s]=a[s]+m.getsize ()-j;
System.out.println (Hashtable.get (j));
System.out.println (A[s]); }

}

 

You can select no more than one option (because the jlist can be selected by the previous setting) List.setselectedindices (a); catch (Exception e) {}} if (Event.getsource () ==btn4) {//int J;//for (J=0;j<m.length (); j +)//{//if (hashtabl 
E.containsvalue (Integer.parseint (j) + "*")//hashtable.put (J,//}}, public void ValueChanged (Listselectionevent event)

{System.out.println (List.getselectedindex ());}

 }

Through these two instances, we have a certain understanding of the Java Fuzzy Query method, I hope you like the small series of articles, continue to pay attention to Oh!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.