在C#的中,可以使用params Parameter[] values给方法动态获取sql语句中的参数值数组。
例如:
private static Book GetBookBySql(string safeSql, params SqlParameter[] values)
{
using (SqlDataReader reader = GetReader(safeSql, values))
{
if (reader.Read())
{
Book book = new Book();
book.Id = (int)reader["Id"];
book.Title = (string)reader["Title"];
book.Author = (string)reader["Author"];
book.PublishDate = (DateTime)reader["PublishDate"];
book.ISBN = (string)reader["ISBN"];
book.WordsCount = (int)reader["WordsCount"];
book.UnitPrice = (decimal)reader["UnitPrice"];
book.ContentDescription = (string)reader["ContentDescription"];
book.AurhorDescription = (string)reader["AurhorDescription"];
book.EditorComment = (string)reader["EditorComment"];
book.TOC = (string)reader["TOC"];
book.Clicks = (int)reader["Clicks"]; book.Category = CategoryService.GetCategoryById((int)reader["CategoryId"]);
book.Publisher = PublisherService.GetPublisherById((int)reader["PublisherId"]); return book;
}
else
{
reader.Close();
return null;
}
}
}public static SqlDataReader GetReader(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
Java中是否也有类似的方法吗,貌似使用PreparedStatement对于数据类型多且混杂的就很难通过方法传递参数?
例如:
private static Book GetBookBySql(string safeSql, params SqlParameter[] values)
{
using (SqlDataReader reader = GetReader(safeSql, values))
{
if (reader.Read())
{
Book book = new Book();
book.Id = (int)reader["Id"];
book.Title = (string)reader["Title"];
book.Author = (string)reader["Author"];
book.PublishDate = (DateTime)reader["PublishDate"];
book.ISBN = (string)reader["ISBN"];
book.WordsCount = (int)reader["WordsCount"];
book.UnitPrice = (decimal)reader["UnitPrice"];
book.ContentDescription = (string)reader["ContentDescription"];
book.AurhorDescription = (string)reader["AurhorDescription"];
book.EditorComment = (string)reader["EditorComment"];
book.TOC = (string)reader["TOC"];
book.Clicks = (int)reader["Clicks"]; book.Category = CategoryService.GetCategoryById((int)reader["CategoryId"]);
book.Publisher = PublisherService.GetPublisherById((int)reader["PublisherId"]); return book;
}
else
{
reader.Close();
return null;
}
}
}public static SqlDataReader GetReader(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
Java中是否也有类似的方法吗,貌似使用PreparedStatement对于数据类型多且混杂的就很难通过方法传递参数?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货