【发布时间】:2021-09-06 22:43:11
【问题描述】:
首先我会说我非常不擅长编码(尚未学习如何利用类以及它们如何深入工作),并且在做这个项目之前我从未使用过 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();
}
【问题讨论】:
-
点击按钮时会显示什么异常或错误。例如在保存过程中
-
也许这SqlCommandBuilder example 有帮助。
-
几年前我创建了an example project on github 来演示带有winforms 和适配器的CRUD。它可能对你有用作为参考。不要因为使用 Sqlite 而被绊倒,在您自己的项目中,您只需使用 Sqlxxx 等价物:SqliteCommand 变为 SqlCommand,等等。