如何通过申请表将项目添加到现有数据库
How to add items to existing database thru application form
我目前有一个数据集,并希望不断向该数据集添加新项目(例如在文本框中键入新条目并使用按钮添加它)并通过我创建的应用程序表单编辑当前项目。
我将如何着手解决这个问题?
编辑:
这是我在观看视频和经历 google 时所能想到的最好的开始。 Dictionary.mdf 是我的数据集
SqlCommand cmd = new SqlCommand("insert into dictionary(word, definition) values(@word, @definition)");
cmd.Parameters.AddWithValue("@word", textBoxWordtoAdd.Text);
cmd.Parameters.AddWithValue("@definition", textBoxDefinition.Text);
this.Close();
我认为你错过了 cmd.ExecuteNonQuery();
如果您使用 Sql 女士服务器。那么您的代码应该如下所示:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string sql = "insert into dictionary(word, definition) values(@word, @definition)";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.Add("@word", SqlDbType.Varchar, 50).value = textBoxWordtoAdd.Text;
cmd.Parameters.Add("@definition", SqlDbType.Varchar, 50).value = textBoxDefinition.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
您还需要打开一个我在您的代码中没有看到的连接,但我假设您在某个地方做了它。只需将代码中的 ConnectionString
替换为您自己的连接字符串即可。
我目前有一个数据集,并希望不断向该数据集添加新项目(例如在文本框中键入新条目并使用按钮添加它)并通过我创建的应用程序表单编辑当前项目。
我将如何着手解决这个问题?
编辑: 这是我在观看视频和经历 google 时所能想到的最好的开始。 Dictionary.mdf 是我的数据集
SqlCommand cmd = new SqlCommand("insert into dictionary(word, definition) values(@word, @definition)");
cmd.Parameters.AddWithValue("@word", textBoxWordtoAdd.Text);
cmd.Parameters.AddWithValue("@definition", textBoxDefinition.Text);
this.Close();
我认为你错过了 cmd.ExecuteNonQuery();
如果您使用 Sql 女士服务器。那么您的代码应该如下所示:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string sql = "insert into dictionary(word, definition) values(@word, @definition)";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.Add("@word", SqlDbType.Varchar, 50).value = textBoxWordtoAdd.Text;
cmd.Parameters.Add("@definition", SqlDbType.Varchar, 50).value = textBoxDefinition.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
您还需要打开一个我在您的代码中没有看到的连接,但我假设您在某个地方做了它。只需将代码中的 ConnectionString
替换为您自己的连接字符串即可。