简体   繁体   English

ASP.NET C#数据库连接不起作用

[英]Asp.Net C# database connection not working

I have this connection string in my web.config : 我的web.config有此连接字符串:

<connectionStrings>
    <add name="SQLServerConnectionString"
         connectionString= "..."
         providerName="System.Data.SqlClient" />
</connectionStrings>

And this simple C# code to pull from the db: 这是从数据库中提取的简单C#代码:

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>");
    }
}

However, I get an error: 但是,我得到一个错误:

The name 'dbAD' does not exist in the current context 名称“ dbAD”在当前上下文中不存在

I take it I need to define dbAD , or a few other variables before hand, but I'd only be guessing. 我认为我需要先定义dbAD或其他一些变量,但是我只是在猜测。

Thanks in advance! 提前致谢!

try this code: 试试这个代码:

i up: 我起来:

        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();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM