[java]代码库
import java.sql.*;
import java.util.*;
public class Example14_6 {
public static void main(String args[]) {
System.out.println("姓名中包含有:张,李或酒的记录:");
PatternQuery patternQuery=new PatternQuery();
patternQuery.setNameContain("张李酒");
String datasorce="star";
String tableName="employee";
patternQuery.setDatasourceName(datasorce);
patternQuery.setTableName(tableName);
ArrayList<StringBuffer> result=patternQuery.getQueryResult();
for(StringBuffer str:result) {
System.out.println(str);
}
}
}
import java.util.*;
public class PatternQuery extends Query {
String nameContain;
public void setNameContain(String s) {
nameContain=s;
}
public ArrayList <StringBuffer> getQueryResult() {
String sql="SELECT * FROM "+tableName+" WHERE name LIKE '%["+
nameContain+"]%'";
setSQL(sql);
return super.getQueryResult();
}
}
import java.sql.*;
import java.util.*;
public class Query {
String datasourceName=""; //数据源名
String tableName=""; //表名
String SQL; //SQL语句
ArrayList <StringBuffer> queryResult; //查询结果
public Query() {
try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e) {
System.out.print(e);
}
}
public void setDatasourceName(String s) {
datasourceName=s.trim();
}
public void setTableName(String s) {
tableName=s.trim();
}
public void setSQL(String SQL) {
this.SQL=SQL;
}
public ArrayList <StringBuffer> getQueryResult() {
queryResult=new ArrayList<StringBuffer>();
Connection con;
Statement sql;
ResultSet rs;
try {
String uri="jdbc:odbc:"+datasourceName;
String id="";
String password="";
con=DriverManager.getConnection(uri,id,password);
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int 字段个数=0;
while(rs1.next()) {
字段个数++;
}
sql=con.createStatement();
rs=sql.executeQuery(SQL);
while(rs.next()) {
StringBuffer record=new StringBuffer();
for(int k=1;k<=字段个数;k++) {
record.append(" "+rs.getString(k)+" ");
}
queryResult.add(record);
}
con.close();
}
catch(SQLException e) {
System.out.println("请输入正确的表名"+e);
}
return queryResult;
}
}