我在使用 C# 表单更新数据库时遇到问题。我正在使用两个富文本框,一个是只读的,其中包含从我的数据库 (richTextBox) 中检索到的数据。 另一个 richtextbox 将用于允许将数据输入数据库 (richTextBox1)。当我的表单加载时,数据库中的数据被加载到只读文本框中。然后可以将数据写入 richTextBox1,然后在我按下“编辑”按钮后将其附加到数据库。
我遇到的问题是输入的新数据没有将数据附加到数据库,而是覆盖了旧数据。从我读过的资料来看,似乎没有办法附加数据,只能替换数据。 我的代码如下:
从数据库中获取数据的代码:
private void QuizForm_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\Quiz.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT DataToRead FROM QuizQuestions";
richTextBox.Text = cmdGet.ExecuteScalar().ToString();
conGet.Close();
}
将数据保存到数据库的代码:
private void btnEdit_Click(object sender, EventArgs e)
{
//richTextBox.Enabled = true;
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\Quiz.accdb";
//declare Connection, command and other related objects
OleDbConnection conSave = new OleDbConnection(cnString);
OleDbCommand cmdSave = new OleDbCommand();
try
{
//open connection
conSave.Open();
cmdSave.CommandType = CommandType.Text;
cmdSave.Connection = conSave;
cmdSave.CommandText = "UPDATE QuizQuestions SET DataToRead = @prichTextBox";
OleDbParameter parrichTextBox1 = new
OleDbParameter("@prichTextBox", OleDbType.VarChar);
parrichTextBox1.Value = (richTextBox.Text + richTextBox1.Text);
cmdSave.ExecuteNonQuery();
//cmdSave.Parameters.Add("@parrichTextBox1", OleDbType.VarChar, combinedTextBox);
conSave.Close();
//END OF MY CODE
}
总而言之,这就是我希望发生的事情: 1. 表单打开,richTextBox自动填充数据库内容 2. 在 richTextBox1 中输入数据/文本,按下“编辑”按钮,导致该数据被附加到数据库中。 3.当窗体重新打开时,添加的数据在只读文本框richTextBox中可见
最佳答案
您的 SQL 语句确实覆盖了数据。 如果您想将 richTextBox 中存在的数据附加到已从数据库读取的记录中,您的 UPDATE SQL 语句应如下所示:
UPDATE QuizQuestions SET DataToRead = DataToRead + @prichTextBox
关于c# - 富文本框追加查询 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6552289/