java连接sqlserver怎么实现模糊查询?

吃草的胖猫 2016-12-10 10:02:31
这个是链接sqlserver的,package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Dao {
protected static String dbClassName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
protected static String dbUrl = "jdbc:microsoft:sqlserver://127.0.0.1:1433;" + "DatabaseName=tsglxt;";
//127.0.0.1为IP地址,1433为接口;tsglxt是数据库名
protected static String dbUser = "sa";//登录名
protected static String dbPwd = "";//登录密码
private static Connection conn = null;//定义一个静态数据库连接
/*
*
*/
private Dao() {// 获得数据库连接
try {
if (conn == null) {
Class.forName(dbClassName).newInstance();//装载数据库驱动
conn = DriverManager.getConnection(dbUrl,dbUser,dbPwd);
} else
return;
} catch (Exception e) {
e.printStackTrace();
}
}

static ResultSet executeQuery(String sql) {// 执行查询操作
try {
if (conn == null)
new Dao();
return conn.createStatement().executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}

static int executeUpdate(String sql) {// 执行其他操作

try {
if (conn == null)
new Dao();
return conn.createStatement().executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}

public static void close() {// 关闭连接
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
}
问题在这里,没有反应完全,查询不了也没有显示出错

//按出版社查询-模糊查询
public static List<Book> selectBookByPublish(String Publish) {
List<Book> list = new ArrayList<Book>();
String sql = "select ISBN,typeid,bookname,author,publish,publishdate,printtime,unitprice,typename from book join booktype on book.typeid=booktype.booktypeid and publish like '%'" +Publish + "'%'";感觉是这里出错了
ResultSet rs = Dao.executeQuery(sql);
try {
while (rs.next()) {
Book Book = new Book();
Book.setISBN(rs.getString("ISBN"));
Book.setBooktypeid(rs.getInt("typeid"));
Book.setBookname(rs.getString("bookname"));
Book.setAuthor(rs.getString("author"));
Book.setPublish(rs.getString("publish"));
Book.setPublishdate(rs.getDate("publishdate"));
Book.setPrinttime(rs.getInt("printtime"));
Book.setUnitprice(rs.getDouble("unitprice"));
Book.setBooktypename(rs.getString("typename"));
list.add(Book);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;

}
...全文
489 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gzcitizeny 2016-12-12
  • 打赏
  • 举报
回复
and publish like '%'" +Publish + "'%'" 应该是and publish like '%" +Publish + "%'",百分号的后和前都不要加单引号。
爱睡觉的阿狸 2016-12-10
  • 打赏
  • 举报
回复
把你标红处的语句改一下放到数据库的查询界面运行一下,查不到值的话,那就是此情况下没有值。
游一游走一走 2016-12-10
  • 打赏
  • 举报
回复
请在此处之后打印SQL语句,然后直接在数据库执行语句,看是否有记录,我怀疑本来就没数据

String sql = "select ISBN,typeid,bookname,author,publish,publishdate,printtime,unitprice,typename from book join booktype on book.typeid=booktype.booktypeid and publish like '%'" +Publish + "'%'";
System.out.println(sql);

58,454

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧