C# 从数据库获取数据并在gridview(asp.net)中显示
我有一个数据库(SQL server)并将其添加到我的网页项目中,但问题是我无法在C# 从数据库获取数据并在gridview(asp.net)中显示,c#,asp.net,sql-server,gridview,webforms,C#,Asp.net,Sql Server,Gridview,Webforms,我有一个数据库(SQL server)并将其添加到我的网页项目中,但问题是我无法在gridview中显示数据 这是我的密码: string query; SqlCommand SqlCommand; SqlDataReader reader; int sindex=DropDownList1.SelectedIndex+1; int hindex =DropDownList3.SelectedIndex+1; SqlDataAdapter adapter = new SqlDataAdapter
gridview
中显示数据
这是我的密码:
string query;
SqlCommand SqlCommand;
SqlDataReader reader;
int sindex=DropDownList1.SelectedIndex+1;
int hindex =DropDownList3.SelectedIndex+1;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();
query = string.Format("select * from table where clumn='"+s+"' ", s);
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);
reader = SqlCommand.ExecuteReader();
GridView2.DataSource = reader;
GridView2.DataBind();
改变这个
query = string.Format("select * from table where clumn='"+s+"' ", s);
对此
query = string.Format("select * from table where clumn='{0}' ", s);
改变这个
query = string.Format("select * from table where clumn='"+s+"' ", s);
对此
query = string.Format("select * from table where clumn='{0}' ", s);
更好地使用:
更好地使用:
使用SqlParameters,而不是像现在这样操作字符串。
另外,请使用语句正确处理对象。
不要使用
select*
,因为这会影响性能,只选择所需的列。下面是您的代码示例,已修改:
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "select column, column2 from table where column=@column";
command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
command.Parameters["column"].Value = yourColumnValue;
conn.Open();
using (SqlDataReader sdr = sco.ExecuteReader())
{
GridView2.DataSource = sdr;
GridView2.DataBind();
}
}
使用SqlParameters,而不是像现在这样操作字符串。
另外,请使用语句正确处理对象。
不要使用
select*
,因为这会影响性能,只选择所需的列。下面是您的代码示例,已修改:
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "select column, column2 from table where column=@column";
command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
command.Parameters["column"].Value = yourColumnValue;
conn.Open();
using (SqlDataReader sdr = sco.ExecuteReader())
{
GridView2.DataSource = sdr;
GridView2.DataBind();
}
}
实际上,只使用参数。实际上,只使用参数。