我會建議先檢查,看看是否在關鍵的表存在,如不及時補充,並得到新的主鍵,如果存在,那麼做無非通知用戶等。
在這裏我有一個醫院科室的表格(只有兩列來保持簡單)。
這裏我使用一個類來保持數據操作與表單分離。
using System;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public class Operations
{
/// <summary>
/// Replace with your SQL Server name
/// </summary>
private string Server = "KARENS-PC";
/// <summary>
/// Database in which data resides, see SQL_Script.sql
/// </summary>
private string Catalog = "ForumExamples";
/// <summary>
/// Connection string for connecting to the database
/// </summary>
private string ConnectionString = "";
/// <summary>
/// Setup the connection string
/// </summary>
public Operations()
{
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True";
}
public bool InsertDepartment(string pDepartment, ref int pIdentifier)
{
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "SELECT Name FROM Departments WHERE Name = @Name";
cmd.Parameters.AddWithValue("@Name", pDepartment);
cn.Open();
if (cmd.ExecuteScalar() == null)
{
cmd.CommandText = @"
INSERT INTO dbo.Departments (Name)
VALUES (@Name); SELECT CAST(scope_identity() AS int);";
pIdentifier = Convert.ToInt32(cmd.ExecuteScalar());
return true;
}
else
{
return false;
}
}
}
}
}
}
表格代碼,一個按鈕,一個文本框
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtDepartmentName.Text))
{
int id = 0;
Operations ops = new Operations();
if (ops.InsertDepartment(txtDepartmentName.Text, ref id))
{
MessageBox.Show($"Id for '{txtDepartmentName.Text}' is {id}");
}
else
{
MessageBox.Show($"Department '{txtDepartmentName.Text}' is already in the database table");
}
}
else
{
MessageBox.Show("Please enter a department name");
}
}
}
上面的代碼的某些部分是用於SQL - 服務器例如MS-Access或其他數據庫可以通過一些修改來獲取新的主鍵。
聽起來像objConnect.UpdateDatabase試圖插入而不是更新?但我們無法知道該方法在做什麼。 – Crowcoder
這裏是類https://jsfiddle.net/o1cd14xv/ – RTX
嘗試運行簡單的更新命令而不是使用數據適配器,您正在向數據集添加行並嘗試更新它,但是在更新後您不刷新數據集。 – Krishna