Code Description: Returns the foreground field as a query condition, returning a qualifying record.
1 PackageCom.imooc.dao;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 Importjava.sql.PreparedStatement;6 ImportJava.sql.ResultSet;7 Importjava.sql.SQLException;8 Importjava.util.ArrayList;9 Importjava.util.List;Ten One ImportCom.imooc.bean.Message; A - /** - * Handle database-related query operations the * - */ - Public classMessagedao { - PublicList<message>querymessagelist (String command,string description) { +List<message> messagelist =NewArraylist<message>(); - Try { +Class.forName ("Com.mysql.jdbc.Driver"); AConnection conn = drivermanager.getconnection ("Jdbc:mysql://127.0.0.1:3306/micro_message", "root", "admin"); at //StringBuilder speed is fast for single-threaded, StringBuffer is suitable for multi-threaded operation of large amounts of data, each time the string is generated new objects, need garbage collection. -StringBuilder SB =NewStringBuilder ("Select id,command,description,content from Message where 1=1"); - //String sql = "Select id,command,description,content from Message"; -list<string> paramlist =NewArraylist<string>(); - if(NULL! = Command &&! "". Equals (command) { -Sb.append ("and command=?")); in paramlist.add (command); - } to if(NULL! = Description &&! "". Equals (description)) { + //use% in MySQL to denote any character, with a space for connection -Sb.append ("and DESCRIPTION like '% '? ') %‘"); the Paramlist.add (description); * } $PreparedStatement pstmt =conn.preparestatement (sb.tostring ());Panax Notoginseng for(intI=0;i<paramlist.size (); i++){ - //Append value to pre-Execute SQL statement in PreparedStatement thePstmt.setstring (i+1, Paramlist.get (i)); + } AResultSet rs =pstmt.executequery (); the while(Rs.next ()) { +Message message =NewMessage (); -Messagelist.add (message);//here messagelist is a container, just a reference to the message, so you can put it in the container in advance . $Message.setid (rs.getstring ("ID")); $Message.setcommand (rs.getstring ("COMMAND")); -Message.setdescription (rs.getstring ("DESCRIPTION")); -Message.setcontent (rs.getstring ("CONTENT")); the } -}Catch(ClassNotFoundException e) {Wuyi e.printstacktrace (); the}Catch(SQLException e) { - e.printstacktrace (); Wu } - returnmessagelist; About } $ - } -
Java connects MySQL database with JDBC