我有一个按钮,每次单击此按钮时,只要我在文本框中引入的文本不在数据库中,新行就会添加到数据库中。否则,我会收到错误(类似于 - 的主键是重复键(“我成功添加到数据库中的最后一行”)。我点击按钮后出现此错误,即使我在文本框中引入的文本不在数据库中,我也有重新启动程序,然后再次..问题是什么?
private void button2_Click(object sender, EventArgs e)
{
DataRow rows = ds.Tables[0].NewRow();
//this is primary key
rows[2] = textBox4.Text;
ds.Tables[0].Rows.Add(rows);
try
{
//updating database.
objConnect.UpdateDatabase(ds);
MessageBox.Show("Record Saved");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
答案 0 :(得分:0)
您可以使用以下语法重写代码。有很多复杂的方法可供选择,但由于你是C#的初学者,我认为这对你来说是最好的。
// Create connection object
SqlConnection connection = new SqlConnection("ConnectionStringtoYourDB");
SqlCommand command = connection.CreateCommand();
try {
// Open the connection.
connection.Open();
// Execute the insert command.
command.CommandText = String.Concat("INSERT INTO Your_Tbl(FirstName) VALUES('", textBox4.Text,"')");
command.ExecuteNonQuery();
MessageBox.Show("Record Saved");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
finally {
// Close the connection.
connection.Close();
}
答案 1 :(得分:0)
我建议首先检查一下表中是否存在密钥,如果没有添加它并获取新的主键,如果存在,则除了通知用户之外什么都不做。
我在这里有一张医院科室的表格(只有两个栏目可以保持简单)。
这里我使用一个类来保持数据操作与表单分离。
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-Server,例如:如何通过稍微修改来检索新主键,可以使用MS-Access或其他数据库完成。