using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient; // need this for database connection
namespace DatabaseTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void connectButton_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = "Server= xxx; Database= nba_database; Integrated Security=True"; // xxx is a placeholder, my connection string is right. Censoring it for privacy
cnn = new SqlConnection(connectionString);
cnn.Open();
MessageBox.Show("Connection Established!");
cnn.Close();
}
private void displayButton_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = "Server= myServer; Database= nba_database; Integrated Security=True";
cnn = new SqlConnection(connectionString);
cnn.Open();
MessageBox.Show("Connection Established!");
// lets query some data from the sql server
// define variables
SqlCommand command;
SqlDataReader dataReader;
String sql, output = "";
// define SQL statement!
sql = "SELECT FirstName, LastName " +
"FROM Players, Teams " +
"WHERE Players.TeamID = Teams.TeamID " +
"AND Teams.Nickname = 'Hawks'";
String sql2 = "SELECT FirstName, LastName FROM Players WHERE Team = 'Milwaukee Bucks'";
// command statement
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
// Get table values
textBox1.Text = command.ExecuteScalar().ToString();
cnn.Close();
dataReader.Close();
command.Dispose();
}
}
}
我正在尝试将 C# Visual Studio 应用程序连接到 SQL Server 数据库,但出现此错误:System.InvalidOperationException:“已经有一个打开的 DataReader 与此命令关联,必须先关闭。”
当用户单击显示按钮时,我希望能够将查询结果返回到 c# 应用程序中的文本框。
错误在这一行 textBox1.Text = command.ExecuteScalar().ToString();