我有这个连接字符串在我的web.config
:
<connectionStrings>
<add name="SQLServerConnectionString"
connectionString= "..."
providerName="System.Data.SqlClient" />
</connectionStrings>
和这个简单的c#代码从db:
dbAD.SelectCommand = new OleDbCommand("SELECT * FROM Profile ORDER BY FullName ASC", dbConnect);
dbAD.Fill(dbRS, "Profile");
if (dbRS.Tables("Profile").Rows.Count > 0)
{
foreach (DataRow employee in dbRS.Tables("Profile").Rows)
{
Response.Write("Employee: " + Profile("FullName") + " " + Profile("Academy") + "<p>");
}
}
但是,我得到一个错误:
名称'dbAD'在当前上下文中不存在
我认为我需要事先定义dbAD
或其他一些变量,但我只是猜测。
提前感谢!
试试下面的代码:
我: using System.Data;
using System.Data.OleDb;
using System.Web.Configuration;
OleDbConnection oledbCnn=null;
OleDbDataAdapter oledbAdapter = null;
DataSet ds=null;
string connetionString = WebConfigurationManager.ConnectionStrings["SQLServerConnectionString"].ConnectionString;
string sql = "SELECT * FROM Profile ORDER BY FullName ASC";
try
{
oledbCnn = new OleDbConnection(connetionString);
oledbCnn.Open();
oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
ds = new DataSet();
oledbAdapter.Fill(ds, "Profile");
foreach (DataRow row in ds.Tables["Profile"].Rows)
{
Response.Write("Employee: " + " " + row["FullName"].ToString() + " " + row["Academy"].ToString() + "<p>");
}
oledbCnn.Close();
}
catch (Exception ex)
{
Response.Write("Can not open connection ! ");
}
finally
{
if (oledbCnn != null) oledbCnn.Dispose();
if (oledbAdapter != null) oledbAdapter.Dispose();
if (ds != null) ds.Dispose();
}