新手求救
解决方案 »
- HTTP 错误 404 - 文件或目录未找到。
- 基础提供程序在 Open 上失败
- 后台接收form提交的页面,怎么获取提交页面的地址
- JScript FileUpload Cancel
- 各位老师.我用的是xp 操作系统,在xp 中如何运行自已写的Asp文件?
- 上传DOC文件到服务器安全如何设定?
- 怎样在页面中嵌入ppt,让ppt自动循环播放
- 为何打印不一样?
- 简单的问题:这两个方法合并到一起怎么写???
- 请各位帮帮忙:用户在测试时用“<br>”这种HTML语言输入到TextBox中进行测试
- GridView1_RowDataBound触发的问题
- GridView导出xls时,当SELECT top 567正常,大于567出现乱码,请指教.
select top 20 * from tablename order by newid()
这样是能随机抽取二十条记录
select * from 题库 order by newid() 试试
不好意思写错了
把表内的字段全部封装好,中间的封装过程省略。然后在DAL层(数据访问层)写如下代码//下面根据传送的科目id编号来查询所选科目下的题目的总数 public int length(int SubjectId)
{
//构建查询语句,通过科目id编号来查询所选科目下的题目总数,这个将变成你随即抽取范围值
string sql = string.Format("select count(*) from Question where SubjectId={0}", SubjectId);
int length= 0;
//我的连接字符串语句是单独写在一个类里面的,你可以把 DbHelp.connStr替换成你的连接字符串
using (SqlConnection connection = new SqlConnection(DbHelp.connStr))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
length =(int)command.ExecuteScalar();
}
}
return length;
} //下面根据传送过来的科目id 把所有信息获取装到传入的数组中间 public List<Question> AllQuestionIds(int SubjectId)
{
String sql = string.Format("select * from question where SubjectId={0} ",SubjectId);
using (SqlConnection connection = new SqlConnection(DbHelp.connStr))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
//把获取的信息 一个个通过实体类封装 然后存储到List里面
while (dataReader.Read())
{
Question question=new Question();
question.QuestionId=(int)dataReader[0];
question.Question1 = dataReader[1].ToString();
//底下省略了,你根据你的表实际情况封装 .......
//然后加入到List集合中去,List对象和Question对象自己去new
list.Add(question);
}
}
}
return list;
}
然后你在业务层做随即数获取就行了:public class QuestionManager
{
QuestionService qs = new QuestionService();
List<Question> list = new List<Question>();
Question question = new Question(); public List<Question> SelectQuestion(int SubjectId)
{
int length = qs.length(SubjectId);
List<Question> list = qs.AllQuestionIds(SubjectId);
List<Question> Alist = new List<Question>();
Random random = new Random();
bool[] isTure = new bool[length];
int i = 0;
//循环来获取20个随机题目
while (i < 20)
{
//首先先获取随机下标
int questionIndex = random.Next(length);
//然后判断这个题目是否以选中,选中是 true, 没有是false
if (isTure[questionIndex] ==false)
{
//如果没有选中 就把list装到一个新的list集合中去
Alist.Add(list[questionIndex]); //然后计数器自加
i++; //然后把这个下表元素在数据里面的属性改变为true;
isTure[questionIndex] = true; }
}
return Alist; }
最后在表示层调用就行了。另外一种就是没有分层,直接用数组保存的,方法其实一样,只是要多获取一次题目,并且要装入到数组里面去
这个方法我就不写了,不过你需要数组的随机抽取方法,我再发好了。个人觉得那个方法没有多大含义。