我第一次在这个网站上问一个问题。我在 Visual C# 2008 中创建了一个简单的 windows 窗体,我将两个文本框中的值添加到 access 2010 数据库中的两个字段中。数据库称为TestDatabase.accdb,表是TestTable。两个变量 FirstName 和 Address 分配给 txt.FirstName 和 txt.Address 的 textbox.text 值。在我看来,我还在为 OleDBCommand 类添加参数的语句中将值添加到这两个变量中:
myCommand.Parameters.Add("@FirstName", OleDbType.VarChar).Value = txtName.Text;
所以基本上它正在工作,但我不明白逻辑,因为它似乎不需要使用
FirstName = txtName.Text;
或者
Address = txtAddress.Text;
陈述。如果我从 TextChanged 事件中删除代码,我会收到一些警告。
这是代码:
namespace Test
{
public partial class Form1 : Form
{
private string FirstName;
private string Address;
private void cmdAdd_Click(object sender, EventArgs e)
{
string strSQL = "INSERT INTO TestTable(Name1, Address) VALUES(@FirstName, '@Address')";
// represents an open connection to a data source. Is a class
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\TEMP\\TestDatabase.accdb");
// represents an SQL statement or stored procedure to execute against a data source
//( takes care of passing queries to the database). Is a class.
OleDbCommand myCommand = new OleDbCommand(strSQL, myConnection);
myCommand.Parameters.Add("@FirstName", OleDbType.VarChar).Value = txtName.Text;
myCommand.Parameters.Add("@Address", OleDbType.VarChar).Value = txtAddress.Text;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Something went wrong");
}
finally
{
myConnection.Close();
}
}
private void txtName_TextChanged(object sender, EventArgs e)
{
//IsNullOrEmpty indicates whether the string is null ot an Empty string
//true if the value parameter is null or an empty string(""); otherwise, false
if (string.IsNullOrEmpty(txtName.Text))
{
//has no value
}
else
{
FirstName = txtName.Text;
}
}
private void txtAddress_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtAddress.Text))
{
//has no value
}
else
{
Address = txtAddress.Text;
}
}
}
}