新建一个“连接”按钮,取名btSql_Connect_Click,在按钮Click事件中写如下代码:
//连接SQL Server的test数据库
//string connectionString = "Data Source=localhost;Database=test;uid=sa;pwd=xxx";
string connectionString = "Data Source=localhost;Database=test;Integrated Security=true";
string sql = "select count(*) from Student";
SqlConnection connection = new SqlConnection(connectionString);
if (connection != null)
{
connection.Open();
//SqlCommand对象,执行操作数据录的命令
SqlCommand command = new SqlCommand(sql, connection);
int totalcount = Convert.ToInt32(command.ExecuteScalar());
MessageBox.Show("test表中共有" + totalcount + "条数据");
connection.Close();
}
else
{
MessageBox.Show("连接SQL Server失败!");
}