请教一下,开发一个统计数据行的小窗体(如下图1),但在查询中,总时好时坏,查询同一个数据库,前几次都好,多查询几次就会报错(如下图3,握手错误),另外,查询完一个,再修改登录参数时,想查询另一个数据库时,也会报错(如下图2,sa错误),报错的界面与程序代码如下,请各位给指导一下,谢谢;
private void button5_Click(object sender, EventArgs e)
{
String connectionString = String.Format("server={0};uid={1};pwd={2};", textBoxHost.Text, textBoxUser.Text, textBoxPassword.Text);
string query = "SELECT name from sys.databases where name NOT IN ('master', 'tempdb', 'model', 'msdb')";
SqlConnection sqlconn = new SqlConnection(connectionString);
sqlconn.Open();
//SqlString = "select name from master..sysdatabases";
//加载数据并显示
try
{
MessageBox.Show("数据库连接成功!");
//查询条件和SqlConnection连接
//SqlCommand cmd = new SqlCommand(SqlString, sqlconn);
//数据适配器
//SqlDataAdapter sda = new SqlDataAdapter();
//sda.SelectCommand = cmd;
//DataTable存储数据
//DataTable dt = new DataTable();
//sda.Fill(dt);
//dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("数据库连接失败,请填写准确连接参数");
return;
}
finally
{
conn.Close();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string dbName = reader.GetString(0);
comboBox1.Items.Add(dbName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}