向数据库添加唯一值 [英] Adding Unique values to database
本文介绍了向数据库添加唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须将项目添加到数据库,但是需要确保一项是唯一的.我在这里做什么?
例如,免得说我需要添加100行,每行三列(学校名称idcard_num)
很明显,这里的名称应该唯一,而其余名称可以重复
1我应该创建一个唯一字段,并吐出将抛出给用户的数据库错误吗?
2.添加之前我应该检查每个项目吗?
我有这个
I have to add items to database, but need to make sure that one item is unique. what do i do here?
e.g lest say i need to add 100 rows of three columns each (school name idcard_num)
it is obvious that name should be unique here, while the rest can have duplicates
1 should i create a unique field , and spit out the database errors that will be thrown to the user?
2. should i check each items before adding?
i have this
Dim conn As New SQLiteConnection("Data Source=" & DBPath)
'conn.SetPassword(dbPassword)
conn.Open()
Dim cmd As New SQLiteCommand(conn)
Dim mytransaction As SQLiteTransaction = conn.BeginTransaction()
Try
'// insert courses //
For i = 0 To UBound(oCourses)
cmd = New SQLiteCommand("INSERT INTO courses ([code]," & _
"[title],[unit]) VALUES (@code,@title,@unit)", conn)
cmd.Parameters.AddWithValue("@code", oCourses(i).Code)
cmd.Parameters.AddWithValue("@title", oCourses(i).Title)
cmd.Parameters.AddWithValue("@unit", oCourses(i).Unit)
'Debug.Print(cmd.CommandText)
cmd.ExecuteNonQuery()
Next
mytransaction.Commit()
Return Nothing
Catch ex As Exception
mytransaction.Rollback()
Debug.Print(ex.Message)
Return ex.Message
Finally
cmd.Dispose()
conn.Dispose()
mytransaction.Dispose()
End Try
推荐答案
i建议您采用方法 1 ,但不要直接抛出异常.请在对其进行检查之前,先检查它是否与唯一键相关,并显示一条正确的消息,指出名称已存在于数据库."
i will suggest you to go with approach 1 but do not throw the exception as it is.Check it before like if it''s related to unique key display a proper message saying "Name already exists in the database."
在添加之前检查所有项目将是一项开销.我建议你选择第一名.只需确保正确处理异常,以使用户在看到技术错误时不会惊慌失措. :)
Checking all the items before adding will be an overhead. I suggest you go with #1. Just make sure to handle exceptions properly so users will not freak out when they see technical errors. :)
这篇关于向数据库添加唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文