Quando precisamos desenvolver um método para consultar o banco de dados, geralmente encontramos um problema: não sabemos quais condições o usuário entrará; portanto, como podemos lidar com instruções SQL para que os métodos que desenvolvemos possam funcionar normalmente, independentemente das condições que eles aceitam? No momento, onde '1' = '1' Plus List pode resolver perfeitamente esse problema. Menos bobagem, adicione o código:
// Método da consulta Fuzzy List Public List <Pesso> query () {list <Soper> list = new ArrayList <> (); Conexão con = null; Scanner sc = new scanner (system.in); System.err.println ("Digite o nome:"); Nome da sequência = SC.NextLine (); System.err.println ("Enter ID:"); String id = sc.NextLine (); System.err.println ("Digite tel:"); String tel = sc.NextLine (); System.err.println ("Digite sexo:"); String sex = sc.nextLine (); String sql = "Selecione ID, nome, tel, sexo dos alunos" // Aqui está o truque, razoavelmente splicing string + "onde 1 = 1"; LIST <BECT> LIST1 = NOVA ARRAYLIST <BECT> (); // Use o pacote Commons-Lang if (stringutils.isnotEmpty (nome)) {sql += "e título como?"; list1.add ("%" + nome + "%"); } if (! stringUtils.isEmpty (id)) {sql += "e conteúdo como?"; list1.add ("%" + id + "%"); } if (! stringUtils.isempty (tel)) {sql += "e addr como?"; list1.add ("%" + tel + "%"); } tente {con = dsutlis.getConnection (); // Depois que a instrução SQL é composta, um objeto PST é gerado. Preparado Pstatement Pst = Con.Preparestatement (SQL); // Defina o valor de? for (int i = 0; i <list1.size (); i ++) {pst.setObject (i+1, list.get (i)); } ResultSet rs = pst.executeQuery (); while (rs.Next ()) {Pessoa P = new Person (); p.setId (rs.getString ("id")); p.setName (rs.getString ("nome")); p.setTel (rs.getString ("tel")); P.SetSex (Rs.getString ("Sex"). Equals ("1")? "Masculino": "feminino"); list.add (P); } rs.close (); pst.close (); } catch (Exceção e) {e.printStackTrace (); } finalmente {tente {con.close (); } catch (sqLexception e) {e.printStackTrace (); }} Lista de retorno; } anotação:
1. O código acima opera em um banco de dados Oracle:
Crie alunos da tabela (ID Varchar (32), Nome Varchar (30), Tel Varcher (15), Sex Char (1), Restrint Stud_pk Primária Chave (ID));
2. Use classes de ferramentas para obter conexão
3. Proson é um Javabean
Abaixo está um guia de como usar o Java para fazer resultados de consultas difusas
importar java.io.*; importar Java.awt. // consulta de enlundamento public classe mídia {public static void main (string args []) {jframe frame = new mediaframe (); frame.setDefaultCloseoperation (jframe.exit_on_close); flustrListernExtible (true);}} mídia mídia} extends jframe); slowent.SetLister (true);}} mídia mídia. Jbutton btn; privado jbutton btn1; private jbutton btn2; private jbutton btn3; private jbutton btn4; privado jfileChooser escolhedor; private jtextfieldfield; mapa hashtable = new hashtable () privado; Mediaframe () {Settitle ("Media"); Setsize (600.500); Jmenubar Menu = New Jmenubar (); setjmenubar (Menu); Jlabel Label = New JBel ("Nome da música:"); Text = New JTextfield (); menu.d (LABEL); Jtoolbar (); m = new defaultListModel (); list = new jlist (m); list.setFixedCellWidth (100); list.seSelectionMode (listselectionModel.mull); Jfilechooser (); btn = new jbutton ("add song"); btn.addactionListener (this); btn1 = new jbutton ("excluir canção"); btn1.addactionListener (this); btn2 = new jbutton ("clear list"); track "); btn3.addactionListener (this); btn4 = new jbutton (" classificação "); btn4.addactionListener (this); jpanel painel = new jpanel (); pain.setLayout (novo Gridlayout (5,1)); painel.add (btn); pain.add (btn1); pain.add (btn2); pain.add (btn3); pain.add (btn4); tb.setLayout (novo Gridlayout (1,2)); tb.add (painel); tb.add (painel); add (tb, borderlayout.west);} public void actionPormed (actionEvent event) {if (event.getSource () == btn) {i ++; resultado = chooser.showEndialog (mediaframe.This); if (resultado == jfilechooser.approve_option) {System.out.println (i); string name = chooser.getSelectedFile (). getPath (); string; string; name; int str2 = name.LastIndExof (). name1 = name.substring (str2+1, str1.length ()); // intercepte todas as seqüências antes do último "/" int str3 = name1.LastIndexOf ("."); string name2 = name1.substring (0, str3); // intercepte todos os sufixos de string depois ".". " hashtable.put (i, nome2); m.add (0, hashtable.get (i)); system.out.println (hashtable);}} if (event.getSource () == btn1) {m.RemoveElement (list.getselectedValue ();); system.out.println (m.RemoveLement (list.getSelectedValue (); System; (event.getSource () == Btn2) {System.out.println (m); i = 0; hashtable.clear (); m.clear ();} if (event.getSource () == btn3) {int [] a = new int [m.getSize ()]; tentativa {int j; name = textfield.getText (); System.out.println (m.getSize ()); para (j = 1; j <= m.getSize (); j ++) {padrony p = padring.compile ("^"+name+"+"); // expressão regular seleciona todos os resultados da consulta. (match.find ()) {s ++; // Registre o nó do índice na matriz a [] a [s] = a [s]+m.getSize ()-j; system.out.println (hashtable.get (j)); system.out.println (a [s]); e) {}} if (event.getSource () == btn4) {// int j; // for (j = 0; j <M.Length (); j ++) // {// if (hashtable.containsValue (jeger.parsent (j)+"* valuechanged (evento ListSelectionEvent) {System.out.println (list.getSelectedIndex ());}}Através desses dois exemplos, você tem um certo entendimento dos métodos de consulta Java Fuzzy? Espero que você goste do artigo do editor e continue a segui -lo!