[英]Can't Establish A Connection To SQL Server Using ADO.NET
I'm trying to establish a connection to a local SQL server using this code:我正在尝试使用以下代码建立与本地 SQL 服务器的连接:
dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
dataGridView1.DataSource = sda;
But when I press the button in my form it doesn't show me the data!但是当我按下表单中的按钮时,它不会向我显示数据! What am i doing wrong?我究竟做错了什么?
You need to open the connection with con.Open();
您需要使用con.Open();
打开连接con.Open();
. .
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
con.Open();
Also you had a lot of other problems like you don't dispose your resource which can lead to memory leak and not closing your connection, also you are not filling your adapter.此外,您还有很多其他问题,例如您没有处理资源,这可能导致内存泄漏并且没有关闭连接,而且您没有填充适配器。 Here is optimal way to doing it.这是执行此操作的最佳方法。
using(SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Form;Integrated Security=True";))
{
con.Open();
SqlCommand com = new SqlCommand("select * from Form", con);
using(SqlDataAdapter sda = new SqlDataAdapter(com));
{
DataTable resultTbl = new DataTable();
sda.Fill(resultTbl);
dataGridView1.DataSource = resultTbl;
dataGridView1.DataBind();
}
}
you need something like this你需要这样的东西
dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
con.Open()
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataTable dt=new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;//set it to datatable
dataGridView1.DataBind();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.