简体   繁体   English

如何使用 ADO.Net 连接数据库?

[英]How to connect database using ADO.Net?

In ASP.NET with VS 2008, I want to connect to a Microsoft SQL Server using ADO.Net This is the my connection string:在带有 VS 2008 的 ASP.NET 中,我想使用 ADO.Net 连接到 Microsoft SQL 服务器这是我的连接字符串:

Data Source=.\SQLEXPRESS;AttachDbFilename=E:\JavaScript\App_Data\Database.mdf;Integrated Security=True;User Instance=True

Here's my code:这是我的代码:

OleDbConnection ocon = new OleDbConnection("Provider=SQLOLEDB;"+"Data Source=.\SQLEXPRESS;"+"AttachDbFilename=E:\JavaScript\App_Data\Database.mdf;"+"Integrated Security=True;"+"User Instance=True");
OleDbCommand ocom=new OleDbCommand();
OleDbDataAdapter oda=new OleDbDataAdapter();


protected void Page_Load(object sender, EventArgs e)
{

    ocon.Open();
    ocom.CommandText = "StoredProcedure1";
    ocom.CommandType = CommandType.StoredProcedure;
    ocom.Connection = ocon;
    ocom.ExecuteReader();
    ocon.Close();
}

When I run this, the error occurs in the connection string.当我运行它时,连接字符串中发生错误。 So how to connect the sqlserver database Using ADO.net?那么如何使用ADO.net连接sqlserver数据库呢?

Use System.Data.SqlClient.SqlConnection , as well as SqlCommand and the rest, instead of the OleDb classes.使用System.Data.SqlClient.SqlConnection以及 SqlCommand 和 rest,而不是 OleDb 类。 Also be sure you use using blocks to ensure that your connection is returned to the connection pool when you're done with it.还要确保使用using块来确保在完成连接后将连接返回到连接池。 Also, Tom's suggestion of using connectionstrings.com to figure out the proper connection string for a SqlConnection object is a good one.此外,Tom 建议使用 connectionstrings.com 来确定 SqlConnection object 的正确连接字符串是一个很好的建议。

using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "StoredProcedure1";
        conn.Open();
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // do stuff with the current row
            }
        }
    }
}

Connectionstrings.com is a great resource when you need help with the various options for all sorts of database connections.当您需要有关各种数据库连接的各种选项的帮助时, Connectionstrings.com是一个很好的资源。

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

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