我正在自学基本的 C#,以开发链接到 SQL Server 数据库的应用程序。我正在创建一个非常基本的应用程序,它允许我在表单中输入 2 个值,然后单击按钮插入值。我还想要一个单独的按钮,它可以显示 ConsoleWindow 中表中的所有数据。插入工作完美,我现在唯一的问题是当我单击 ShowData 按钮时没有任何反应,有什么想法吗?
我可以想象这将是一些非常基本的东西,但正如我所说,我仍在学习。
public partial class InsertNames : Form
{
public InsertNames()
{
InitializeComponent();
}
private SqlConnection thisConnection = new SqlConnection("Data Source=(localdb)\\V11.0;database=Dev");
private void FirstName_TextChanged(object sender, EventArgs e)
{
string firstName = FirstName.Text;
}
private void LastName_TextChanged(object sender, EventArgs e)
{
string lastName = LastName.Text;
}
private void Insert_Click(object sender, EventArgs e)
{
try
{
thisConnection.Open();
SqlCommand insertCommand = thisConnection.CreateCommand();
insertCommand.CommandText = "INSERT INTO Names (FirstName,LastName) Values (@FirstName, @LastName)";
insertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = FirstName.Text;
insertCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = LastName.Text;
insertCommand.ExecuteNonQuery();
Console.WriteLine(insertCommand);
thisConnection.Close();
}
catch (SqlException excep)
{
Console.WriteLine(excep.Message);
}
}
private void ShowData_Click(object sender, EventArgs e)
{
try
{
thisConnection.Open();
SqlDataReader myReader = null;
SqlCommand selectCommand = new SqlCommand("Select * from Names", thisConnection);
myReader = selectCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["FirstName"].ToString());
Console.WriteLine(myReader["LastName"].ToString());
}
thisConnection.Close();
}
catch (SqlException excep)
{
Console.WriteLine(excep.Message);
}
}
}