首页 > 解决方案 > 使用 c# winforms 将数据更新/保存到 SQL 数据库表

问题描述

我首先要说我在编码方面非常无能(尚未学习如何利用类以及它们如何深入工作),并且在做这个项目之前我从未使用过 sql。

这里的想法是您连接到一个 sql 数据库,之后 datagridview 元素将填充TABLE_1默认调用的表中的数据。然后用户应该能够输入、删除和保存数据。

前两个工作操作完美运行,但节省是问题所在。我已经用头撞墙了大约 4 天,试图让储蓄发挥作用,但我就是不能这样做。保存是使用方法完成的Button3_click

//initialize the classes I guess, on some youtube guides they did so
SqlConnection con;
DataSet ds;
SqlDataAdapter a;
DataTable t;
SqlCommandBuilder scb;
static string tablename = "TABLE_1";
string constring;

//connect button
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        //connect using info from textboxes, connection is ok
        constring = "server=" + Server.Text + ";database=" + DB.Text + ";UID=" + UID.Text + ";password=" + Password.Text;
        SqlConnection con = new SqlConnection(constring);
        con.Open();
        DataSet ds = new DataSet();
        Save.Enabled = true;
        //check if table name is empty, if so default to TABLE_1
        if (textBox1.Text != "")
        { 
            tablename = textBox1.Text;
        }
        else
        { 
            tablename = "TABLE_1";
        }
        a = new SqlDataAdapter("SELECT * FROM " + tablename, con);
            DataTable t = new DataTable();
            a.Fill(t);
            datagrid.DataSource = t;
        //
        label5.Text = Server.Text;
        con.Close();
    }
    catch(Exception es)
    {
        MessageBox.Show(es.Message);
    }
   
}


//save button
private void button3_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(constring);
    con.Open();
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        a.TableMappings.Add(tablename, "t");
        scb = new SqlCommandBuilder(a);
        a.Update(t);
    con.Close();
}

标签: c#sqlwinforms

解决方案


使用以下示例将适配器、数据集和表名设置为私有变量。

另外,我建议永远不要使用一个字母的变量名,因为 a) 很难调试 b) 当进入更多行代码时,很难知道变量的用途。

接下来,使用 SELECT *,不知道您是否设置了执行更新所需的自动递增主键。在下面的示例中,Id 是自动递增的。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsDataAdapterExample
{
    public partial class Form1 : Form
    {
        private SqlDataAdapter _companiesSqlDataAdapter;
        private DataSet _companiesDataSet;
        private string _tableName = "Companies";
        public Form1()
        {
            InitializeComponent();
            
            Shown += OnShown;
        }

        private void OnShown(object sender, EventArgs e)
        {
            _companiesDataSet = new DataSet();
            
            _companiesSqlDataAdapter = new SqlDataAdapter(
                "SELECT Id, FirstName, LastName, PhoneNumber, City FROM dbo.Companies;",
                "Data Source=.\\sqlexpress;Initial Catalog=ForumExample;" + 
                "Integrated Security=True");

            var builder = new SqlCommandBuilder(_companiesSqlDataAdapter);

            _companiesSqlDataAdapter.Fill(_companiesDataSet, _tableName);

            dataGridView1.DataSource = _companiesDataSet.Tables[_tableName];

        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            _companiesSqlDataAdapter.Update(_companiesDataSet, _tableName);
        }
    }
}

推荐阅读