using System.Data引用这两个命名空间
public string GetData()
{
string strcon = "server=.database=数据库名uid=数据库用户名;pwd=密码"
string sql = "select 需要查询的字段名 from table"
string needData = null
SqlConnection con = new SqlConnection()//创建连接
con.ConnectionString = strcon
SqlCommand cmd = new SqlCommand()//Command对象
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
con.Open()
//执行command
using (SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (sdr.Read())
{
needData += sdr[0].ToString()
}
}
return needData//返回所需字符
}
然后在Page_Load事件中调用这个方法
if (!IsPostBack)
{
Label1.Text = GetData()
}
说明你的sqlselect * from news where id = '" + Request.QueryString["id"] + "'"
读取的记录数是0条,导致执行了Redirect了
用SqlServer数据库为例:SqlConnection conn = new SqlConnection("Data Source=.Initial Catalog=MyDBIntegrated Security=True")conn.Open()
SqlCommand cmd = conn.CreateCommand()
cmd.CommandText = "select * from T_users where UserName='admin'"
SqlDataReader reader=cmd.ExecuteReader()
if (reader.Read())
{
Label1.Text = Convert.ToString(reader["UserName"])
}
conn.Close()说明:此处T_users表示“ABC”数据库表;UserName表示a字段;SQL语句作用是通过a字段获取一条记录(b记录),当然,要获取b记录a字段的值也要以用b记录中的其它字段作为条件。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)