簡體   English   中英

將行添加到數據庫

[英]Adding row into database

我有一個按鈕,每當我單擊此按鈕時,只要我輸入到文本框中的文本不在數據庫中,就會將新行添加到數據庫中。否則,我會收到錯誤消息(類似於-違反主鍵重復的鍵是(“我成功添加到數據庫的最后一行”)。單擊按鈕后,即使我輸入到文本框中的文本不在數據庫中,也遇到此錯誤,我必須重新啟動程序,然后再..什么問題?

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);
    }
}

您可以使用以下語法重寫代碼。 有許多復雜的方法可以使用,但是由於您是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();

    }

我建議先檢查表中是否存在該鍵,如果不添加它並獲取新的主鍵,如果存在,則除了通知用戶外什么也不要做。

在這里,我有一張醫院部門的表格(只有兩列可以使事情變得簡單)。

在這里,我使用一個類來使數據操作與表單分開。

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或其他數據庫來進行新的主鍵稍作修改就可以檢索到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM