如何避免使用VB.net在表中插入重复的Access数据库 [英] How to avoid inserting duplicate Access dataBase in tables using VB.net

查看:102
本文介绍了如何避免使用VB.net在表中插入重复的Access数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨所有

可以帮助以下问题

i想要阻止用户看错误按摩并自定义其他按摩错误索引中的重复值,主键或关系..而且我想要代码来检查重复的数据

请注意我使用Vb.net 2008与AccessData Basee



  Imports  System.Data 
Imports System.Data.OleDb

公开 SpecialColor

公共 CON 作为 OleDbConnection( Provider = Microsoft.Jet.OLEDB.4.0;& 数据源=& Application.StartupPath& \db1.mdb)
公开 DS 正如 DataSet
公共 SQLstr 作为 字符串 = SELECT * FROM SpecialColor WHERE OrderNo LIKE'%& PrintDetails.TextBox1.Text& %'

Sub DataBaseUpdate()
尝试
CON.Open()
Dim DataAdapter1 As OleDbDataAdapter(SQLstr,CON)
DataAdapter1.Fill( DS, SpecialColor
CON.Close()
AddDataContent()
Catch ex As 异常
MsgBox(ex.Message,MsgBoxStyle.MsgBoxRight + MsgBoxStyle.Critical, خطأفيالإتصال
结束 尝试
结束 Sub

公开 Sub updatTheDataBase()
Dim DataAdapter1 As OleDbDataAdapter(SQLstr,CON)
DS.Clear()
DataAdapter1.Fill(DS, SpecialColor
结束 Sub

Sub AddDataContent()

On 错误 恢复 下一步
TextBox3.DataBindings.Add( Text,DS, < span class =code-string> SpecialColor.PrintOn)
TextBox5.DataBindings.Add( Text,DS, SpecialColor.OrderNo
TextBox2.DataBindings.Add( < span class =code-string> Text,DS, SpecialColor.SpecialColor
TextBox4.DataBindings.Add( Text,DS, SpecialColor.Color
TextBox1.DataBindings.Add( Text,DS, SpecialColor .Ref
结束 Sub

Sub InsertData()
尝试

Dim SavInto1 As < span class =code-keyword> New OleDb.OleDbCommand
SavInto1.Connection = CON
SavInto1.CommandType = CommandType.Text
SavInto1.CommandText = 更新SpecialColor设置Color = @ P1,Ref = @ P2其中OrderNo = @ P3和PrintOn = @P4和SpecialColor = @ P5

使用 SavInto1.Parameters
.AddWithValue( @ P1,TextBox4.Text)
.AddWithValue( @ P2,TextBox1.Text)
.AddWithValue( @ P3 ,TextBox5.Text)
.AddWithValue( @ P4,TextBox3.Text)
.AddWithValue( @ P5,TextBox2.Text)
结束 使用
CON.Open()
SavInto1.ExecuteNonQuery()
CON.Close()
MsgBox( تمتعمليةالاضافةوالحفظفيقاعدةالبياناتبنجاح,MsgBoxStyle.Information, < span class =code-string>تمتالعمليةبنجاح)
Catch ex As 异常何时 SQLstr.Count> 0
MsgBox( 此记录全部更新,MsgBoxStyle.Critical, 错误
CON.Close( )
Catch ex As Exception
MsgBox(Err.Description,MsgBoxStyle.Critical , 错误
结束 尝试
结束 Sub

私有 Sub Button3_Click( ByVal 发​​件人作为系统。对象 ByVal e As System.EventArgs)句柄 Button3.Click
InsertData()
如果 Me .BindingContext(DS, SpecialColor)。Position = Me .BindingContext(DS, SpecialColor)。计数 - 1 然后
MyBase .Close()
否则
.BindingContext(DS, SpecialColor)。位置+ = 1
结束 如果
结束 Sub

私有 Sub SpecialColor_Load( ByVal sender As System。 Object ByVal e As System.EventArgs) Handles MyBase .Load
Me .Text = 订单号打印详情& PrintDetails.TextBox1.Text
TextBox3。 ReadOnly = True
TextBox2。 ReadOnly = True
TextBox5。 ReadOnly = True
DataBaseUpdate()
如果 .BindingContext(DS, SpecialColor)。Count> = < span class =code-digit> 2 然后
Button3.Enabled = True
Button4.Enabled = True
否则
Button3。 Enabled = False
Button4.Enabled = False
结束 如果



结束 Sub

私有 Sub Button4_Click( ByVal sender As System 。对象 ByVal e 作为系统。 EventArgs)句柄 Button4.Click
Me .BindingContext(DS, SpecialColor)。位置 - = 1
< span class =code-keyword> End Sub

Private Sub Button2_Click( ByVal 发​​件人作为系统。对象 ByVal e As System.EventArgs)句柄 Button2.Click
InsertData( )
MyBase .Close()
结束

结束

解决方案

大多数SQL查询都适用于Access数据库,因为Access前端主要使用SQL查询来处理其数据,所以是的,应该是在使用Access数据库时能够使用IF EXISTS。 (常规信息链接:访问和SQL [ ^ ])



在你的VB代码中,你应该实现Try Catch Finally块所以你可以做正确的错误处理。



一般格式如下:



 尝试 
..代码...
Catch 例外作为键入
....代码工作 with 期望异常...
Catch 异常 as system.exception
....代码 处理意外异常....
最后
...清理代码....
结束 尝试







更多详情关于这一点可以从谷歌和 MSDN [ ^ ]





ADO.Net对象(在您的代码示例中为OLEDB ....对象)很好地抛出您可以捕获的特定错误类型。然后,您可以在异常消息中查找关键字/短语,并向用户显示用户友好的消息。



此外,如果您要实施用于插入新记录的IF EXISTS方法,如果已经存在,则可以从中返回-1,如果不存在则返回插入后的指定ID。这样你就不必有一个捕获来查找副本,而只是处理查询的结果。



有很多可用的资源互联网提供了所有这些概念的例子,因此没有详细说明,但强调可能的方法,这些方法可以帮助您找到可以在代码中使用的示例。


我的工作解决了我的问题问题在这里,我得到下面的代码,但它没有保存任何数据,当你有重复的数据,你可以看看它并尝试帮助



  Sub  InsertData()
尝试
Dim SQLstr 作为 字符串 = SELECT * FROM SpecialColor WHERE OrderNo LIKE'%& PrintDetails.TextBox1.Text& %'
Dim selectdb 作为 字符串 = SELECT Ref FROM SpecialColor WHERE OrderNo ='& TextBox5.Text& '和PrintOn ='& TextBox3.Text& '和SpecialColor ='& TextBox2.Text& 'Color ='& TextBox4.Text& ''
Dim DataAdapter1 As OleDbDataAdapter(selectdb,CON)
TextBox6.DataBindings.Clear()
TextBox6.DataBindings.Add( Text,DS, SpecialColor.Ref
If TextBox6.Text< ;> TextBox1.Text 然后
Dim SavInto1 As OleDb.OleDbCommand
SavInto1.Connection = CON
SavInto1.CommandType = CommandType.Text
SavInto1.CommandText = < span class =code-string> 更新SpecialColor set Color = @ P1,Ref = @ P2其中OrderNo = @ P3和PrintOn = @ P4和SpecialColor = @ P5
使用 SavInto1.Parameters
.AddWithValue( @ P1,TextBox4.Text)
.AddWithValue( @ P2,TextBox1.Text)
.AddWithValue( @ P3 ,TextBox5.Text)
.AddWithValue( @ P4,TextBox3.Text)
.AddWithValue( @ P5,TextBox2.Text)
结束 使用
CON.Open()
SavInto1.ExecuteNonQuery()
CON.Close()
MsgBox ( تمتعمليةالاضافةوالحفظفيقاعدةالبياناتبنجاح,MsgBoxStyle.Information, تمتالعمليةبنجاح
ElseIf TextBox6.Text = TextBox1.Text 然后
MsgBox( 这个命令a llreay更新了,MsgBoxStyle.Critical, 错误
TextBox1。 Clear()
TextBox4.Clear()
CON.Close()
结束 如果
Catch ex As Exception
MsgBox(Err.Description ,MsgBoxStyle.Critical, 错误
结束 尝试
结束


hi all
can some pls help for following issue
i want prevent a user for see error massage and customize other massage for error Duplicate Values in the index,primary key or relationship ..and also i want code to check duplicated data
Please Noted I Used Vb.net 2008 with AccessData Basee

Imports System.Data
Imports System.Data.OleDb

Public Class SpecialColor

    Public CON As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source =" & Application.StartupPath & "\db1.mdb")
    Public DS As New DataSet
    Public SQLstr As String = "SELECT * FROM SpecialColor WHERE OrderNo LIKE '%" & PrintDetails.TextBox1.Text & "%'"

    Sub DataBaseUpdate()
        Try
            CON.Open()
            Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, CON)
            DataAdapter1.Fill(DS, "SpecialColor")
            CON.Close()
            AddDataContent()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.MsgBoxRight + MsgBoxStyle.Critical, " خطأ في الإتصال")
        End Try
    End Sub

    Public Sub updatTheDataBase()
        Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, CON)
        DS.Clear()
        DataAdapter1.Fill(DS, "SpecialColor")
    End Sub

    Sub AddDataContent()

        On Error Resume Next
        TextBox3.DataBindings.Add("Text", DS, "SpecialColor.PrintOn")
        TextBox5.DataBindings.Add("Text", DS, "SpecialColor.OrderNo")
        TextBox2.DataBindings.Add("Text", DS, "SpecialColor.SpecialColor")
        TextBox4.DataBindings.Add("Text", DS, "SpecialColor.Color")
        TextBox1.DataBindings.Add("Text", DS, "SpecialColor.Ref")
    End Sub

    Sub InsertData()
        Try

            Dim SavInto1 As New OleDb.OleDbCommand
            SavInto1.Connection = CON
            SavInto1.CommandType = CommandType.Text
            SavInto1.CommandText = "Update SpecialColor set Color=@P1,Ref=@P2 where OrderNo=@P3 and PrintOn=@P4 and SpecialColor =@P5"

            With SavInto1.Parameters
                .AddWithValue("@P1", TextBox4.Text)
                .AddWithValue("@P2", TextBox1.Text)
                .AddWithValue("@P3", TextBox5.Text)
                .AddWithValue("@P4", TextBox3.Text)
                .AddWithValue("@P5", TextBox2.Text)
            End With
            CON.Open()
            SavInto1.ExecuteNonQuery()
            CON.Close()
            MsgBox("تمت عملية الاضافة والحفظ في قاعدة البيانات بنجاح", MsgBoxStyle.Information, "تمت العملية بنجاح")
        Catch ex As Exception When SQLstr.Count > 0
            MsgBox("This Record allreay updated", MsgBoxStyle.Critical, "Error")
            CON.Close()
        Catch ex As Exception
            MsgBox(Err.Description, MsgBoxStyle.Critical, "Error")
        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        InsertData()
        If Me.BindingContext(DS, "SpecialColor").Position = Me.BindingContext(DS, "SpecialColor").Count - 1 Then
            MyBase.Close()
        Else
            Me.BindingContext(DS, "SpecialColor").Position += 1
        End If
    End Sub

    Private Sub SpecialColor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Text = "Print Details Of Order Number " & PrintDetails.TextBox1.Text
        TextBox3.ReadOnly = True
        TextBox2.ReadOnly = True
        TextBox5.ReadOnly = True
        DataBaseUpdate()
        If Me.BindingContext(DS, "SpecialColor").Count >= 2 Then
            Button3.Enabled = True
            Button4.Enabled = True
        Else
            Button3.Enabled = False
            Button4.Enabled = False
        End If



    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Me.BindingContext(DS, "SpecialColor").Position -= 1
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        InsertData()
        MyBase.Close()
    End Sub

End Class

解决方案

Most SQL Queries will work with an Access Database, as it happens the Access front end uses mainly SQL queries to processes its data, so yes should be able to use IF EXISTS when working with the Access database. (General info link: Access and SQL[^])

In your VB code, you should implement Try Catch Finally blocks so that you can do correct error handling.

The general format is something like:

Try
    ..Code...    
Catch exception As type 
 ....Code to work with expected exception...
Catch exception as system.exception
  ....code to handle unexpected exceptions....
Finally
   ... clean up code....
End Try




Further details on this can be found from Google and from MSDN[^]


the ADO.Net objects (in your code example the OLEDB.... objects) well throw specific error types which you can catch. You can then look for keywords/phrases in the exception message(s) and present user friendly messages back to the user.

In addition, if you were to implement the IF EXISTS method for inserting new records, you could return -1 from it if it already exists or return the assigned ID after the insert if it didn't exists. That way you don't have to have a catch to look for a duplicate, instead just process the result of the query.

There is a lot of available resources on the internet that give examples of all of these concepts, hence not going into detail but highlighting possible approaches which should help you find examples you can use in your code.


I was work for solved my problem here and i get this code below but its not save any data when there duplicate data can you pls look on it and try to help

Sub InsertData()
        Try
            Dim SQLstr As String = "SELECT * FROM SpecialColor WHERE OrderNo LIKE '%" & PrintDetails.TextBox1.Text & "%'"
            Dim selectdb As String = "SELECT Ref FROM SpecialColor WHERE OrderNo = '" & TextBox5.Text & "' and PrintOn = '" & TextBox3.Text & "' and SpecialColor = '" & TextBox2.Text & "' Color = '" & TextBox4.Text & "' '"
            Dim DataAdapter1 As New OleDbDataAdapter(selectdb, CON)
            TextBox6.DataBindings.Clear()
            TextBox6.DataBindings.Add("Text", DS, "SpecialColor.Ref")
            If TextBox6.Text <> TextBox1.Text Then
                Dim SavInto1 As New OleDb.OleDbCommand
                SavInto1.Connection = CON
                SavInto1.CommandType = CommandType.Text
                SavInto1.CommandText = "Update SpecialColor set Color=@P1,Ref=@P2 where OrderNo=@P3 and PrintOn=@P4 and SpecialColor=@P5 "
                With SavInto1.Parameters
                    .AddWithValue("@P1", TextBox4.Text)
                    .AddWithValue("@P2", TextBox1.Text)
                    .AddWithValue("@P3", TextBox5.Text)
                    .AddWithValue("@P4", TextBox3.Text)
                    .AddWithValue("@P5", TextBox2.Text)
                End With
                CON.Open()
                SavInto1.ExecuteNonQuery()
                CON.Close()
                MsgBox("تمت عملية الاضافة والحفظ في قاعدة البيانات بنجاح", MsgBoxStyle.Information, "تمت العملية بنجاح")
            ElseIf TextBox6.Text = TextBox1.Text Then
                MsgBox("This order allreay updated", MsgBoxStyle.Critical, "Error")
                TextBox1.Clear()
                TextBox4.Clear()
                CON.Close()
            End If
        Catch ex As Exception
            MsgBox(Err.Description, MsgBoxStyle.Critical, "Error")
        End Try
    End Sub


这篇关于如何避免使用VB.net在表中插入重复的Access数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆