主题:关于随机选择和判断重复的问题
scan
[专家分:0] 发布于 2005-12-20 20:27:00
如果希望,在一个表中随机选择N个符合某个条件的记录,应该怎么写代码?还请各位大哥给个比较全的代码!我不懂这个!!!!!!
顺便问另外一个问题,比如我通过按钮新增一个记录到表中,但是希望能判断添加的项在本字段里是否有重复,请问该怎么判断?
回复列表 (共8个回复)
沙发
zrs797246 [专家分:190] 发布于 2005-12-21 00:55:00
用绑定的方法可能会比较好解决
板凳
shuiziliu [专家分:300] 发布于 2005-12-21 08:10:00
1、用sql语句就可以了吧
“select * from 表 where 你的条件”
2、也可以用DataView来判断
Dim conn1 As New OleDbConnection
Dim strString As String
strString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb;"
conn1 = New OleDbConnection(strString)
Dim myview As DataView = New DataView(DataSet31.chengji, "xingming='" & TextBox2.Text & "'", "xuehao", DataViewRowState.CurrentRows)
Dim rowindex As Integer = myview.Find(TextBox1.Text)
If rowindex = -1 Then
Dim str As String = "insert into chengji(xuehao,xingming,kemubianhao,kemufenshu,banjimingcheng)values(@xuehao,@xingming,@kemubianhao,@kemufenshu,@banjimingcheng)"
Dim com As OleDbCommand = New OleDbCommand(str, conn1)
com.Parameters.Add("@xuehao", OleDbType.VarChar).Value = TextBox1.Text
com.Parameters.Add("@xingming", OleDbType.VarChar).Value = TextBox2.Text
com.Parameters.Add("@kemubianhao", OleDbType.VarChar).Value = ComboBox1.Text
com.Parameters.Add("@kemufenshu", OleDbType.VarChar).Value = TextBox3.Text
com.Parameters.Add("@banjimingcheng", OleDbType.VarChar).Value = ComboBox2.Text
conn1.Open()
com.ExecuteNonQuery()
conn1.Close()
MsgBox("you can")
Else : MsgBox("you cannot")
End If
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
ComboBox1.Text = ""
ComboBox2.Text = ""
(DataSet31是你绑定所连数据库表的数据集)
3 楼
scan [专家分:0] 发布于 2005-12-21 08:46:00
楼上,关于第一个问题,能说详细一点嘛?比如我想在一个表中随机选5个符合一定规则的记录,一定要是随机哦,应该怎么写代码,非常感谢
4 楼
shuiziliu [专家分:300] 发布于 2005-12-21 09:44:00
"select top 5 字段 from 表名"
随机,俺就不晓得了。
抱歉!
5 楼
scan [专家分:0] 发布于 2005-12-21 10:05:00
top这个我知道,但是我现在想是随机选择~唉
6 楼
shuiziliu [专家分:300] 发布于 2005-12-21 10:10:00
太好了,我知道怎么弄了。
form1中拖过来一个Button 如下:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn1 As New OleDbConnection
Dim strString As String
Dim cmd1 As OleDbCommand
Dim s1 As String
Dim dr1 As OleDbDataReader
strString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb;"
conn1 = New OleDbConnection(strString)
conn1.Open()
Dim R As New Random
Dim intRandomNumber As Integer
intRandomNumber = R.Next(1, 1000)
s1 = "select top 5 xuehao from chengji Order By Rnd(" & (-1 * intRandomNumber).ToString() & " * xuehao)"
cmd1 = New OleDbCommand(s1, conn1)
dr1 = cmd1.ExecuteReader
While dr1.Read
MsgBox(dr1(0))
ComboBox1.Items.Add(dr1(0))
End While
dr1.Close()
conn1.Close()
你再试一下吧
7 楼
scan [专家分:0] 发布于 2005-12-21 12:33:00
不错不错,能解释一下关键部分吗?谢谢
8 楼
shuiziliu [专家分:300] 发布于 2005-12-21 14:26:00
由于Access数据库记录集缓存的原因,从代码里得到Access数据库随机记录是得不到,需要用随机SQL语句的办法来消除缓存。
我来回复