 |
|
สอบถามเรื่อง violation of primary key constraint ในคำสั่ง INSERT & UPDATE |
|
 |
|
|
 |
 |
|
นี้คือ คำสั่ง INSERT ครับ
Code (VB.NET)
If txtidtype.Text = "" Or txttypename.Text = "" Then
MessageBox.Show("กรุณากรอกข้อมูลให้ครบถ้วนด้วยครับ", "คำเตือน", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
Call InsertData()
Dim ssql As String
ssql = "UPDATE DrugsType SET DrugstypeName='" & txttypename.Text & "' WHERE DrugstypeID='" & txtidtype.Text & "'"
Try
dbOpen()
Com = New SqlCommand(ssql, Conn)
If Com.ExecuteNonQuery() = 1 Then
MessageBox.Show("Edit complete.", "Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
dgvdrugtype.DataSource = GetData()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Call ClearData()
End If
|
 |
 |
 |
 |
Date :
2012-05-30 14:41:03 |
By :
TONG |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ลองดู code ของ insert ครับว่ามีอะไรที่เราบันทึกเข้าไปแล้วทำให้ Primary key มันซ้ำรึเปล่า
เอา function InsertData() มาลงให้ดูหน่อยครับ บางทีอาจจะพอช่วยดูได้
เพราะ code ที่เอามาให้ดูเหมือนจะยังไม่ใช่รึเปล่าครับ
|
 |
 |
 |
 |
Date :
2012-05-30 14:51:46 |
By :
Nebula |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
นี้ code INSERTDATA ครับ
Code (VB.NET)
If MessageBox.Show("คุณต้องการเพิ่มข้อมูลลูกค้าใช่หรืไม่", "คำยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
Try
tr = Conn.BeginTransaction
Com.Parameters.Clear()
Dim sql As String = ""
dbOpen()
sql = " Insert Into DrugsType(DrugstypeID, DrugstypeName) values(@1,@2)"
Com = New SqlCommand(sql, Conn)
With Com.Parameters
.Add(New SqlParameter("@1", txtidtype.Text))
.Add(New SqlParameter("@2", txttypename.Text))
End With
Com.ExecuteNonQuery()
Com.Parameters.Clear()
dgvdrugtype.DataSource = GetData()
Catch ex As Exception
tr.Rollback()
MsgBox(ex.Message)
End Try
End If
|
 |
 |
 |
 |
Date :
2012-05-30 14:54:39 |
By :
TONG |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ตาราง DrugsType
DrugstypeID เก็บข้อมูลยังไงครับ เป็น primary key ด้วยรึเปล่าครับ
ถ้าเป็นผมคงทำแบบนี้
ตาราง DrugsType(DTid,DrugstypeID,DrugstypeName,..other..)
โดยให้ DTid เป็น PK และก็เป็น integer และก็ตั้ง autonumber
DrugstypeID เก็บ รหัสประเภทยาก็จริง ก็ยังเก็บได้ เก็บได้หลายแบบด้วย เช่น 1 , 001 , DT00001
เวลาเราแก้ไขก็อ้างอิงจาก DTid จะชัวร์กว่าครับ
|
 |
 |
 |
 |
Date :
2012-05-30 15:34:59 |
By :
Nebula |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|