我的sql是:
select (select count(*) from TblRMember where sex=1) male,
(select count(*) from TblRMember where sex=2) female,
(select count(*) from TblRMember where sex=0) unkown
我希望Dapper.Net像这样返回一个Dictinary:
Keys:male,female,nukown
Value:10,30,50
我看到How to map to a Dictionary object from database results using Dapper Dot Net?,但这不起作用!
如何使用ToDictionary或其他方式实现我想要的
var myDictionary = sqlConnection.Query(strSql).ToDictionary(??);
谢谢!
答案 0 :(得分:5)
首先将您的查询更改为单一查询:
select case when sex = 1 then 'male'
when sex = 2 then 'female'
when sex = 0 then 'unknown'
end as sex, count(*) as cnt
from TblRMember
group by sex
因为我看到sex
是数字,所以你要么必须通过名字(性别名?)选择coumn,要么在你的代码中更改它。之后:
var myDictionary = sqlConnection.Query(strSql)
.ToDictionary(x => x.sex.ToString(), x => (int)x.cnt);
答案 1 :(得分:0)
package task;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/STP")
public class STP extends HttpServlet {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int ID = Integer.parseInt(request.getParameter("ID"));
System.out.println(ID);
String Name = request.getParameter("Name");
String Branch = request.getParameter("Branch");
long Mobile =Long.valueOf(request.getParameter("Mobile"));
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vikas", "root", "root");
CallableStatement cs = con.prepareCall("{call Procedure3(?,?,?,?)}");
cs.setInt(1, ID);
cs.setString(2, Name);
cs.setString(3,Branch);
cs.setLong(4,Mobile);
cs.execute();
int id=cs.getInt(1);
String name=cs.getString(2);
String branch=cs.getString(3);
long mobile=cs.getLong(4);
request.setAttribute("id",id);
request.setAttribute("name",name);
request.setAttribute("branch",branch);
request.setAttribute("mobile",mobile);
request.getRequestDispatcher("StoredProcedure.jsp").forward(request, response);
System.out.println(id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
您可以使用别名和强类型。
别名是关键点,与KeyValuePair类型的键和值的属性匹配。
它在强类型下可以正常运行。
我不喜欢动态类型。在某些情况下会带来灾难。而且,装箱和拆箱都会造成性能损失。