如何使用ADO.Net连接数据库? [英] How to connect database using ADO.Net?

查看:66
本文介绍了如何使用ADO.Net连接数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在带有VS 2008的ASP.NET中,我想使用ADO.Net连接到Microsoft SQL Server这是我的连接字符串:

In ASP.NET with VS 2008, I want to connect to a Microsoft SQL Server using ADO.Net This is the my connection string:

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

这是我的代码:

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

运行此命令时,连接字符串中发生错误.那么如何使用ADO.net连接sqlserver数据库?

When I run this, the error occurs in the connection string. So how to connect the sqlserver database Using ADO.net?

推荐答案

使用 System.Data.SqlClient.SqlConnection ,以及SqlCommand和其余代码,而不是OleDb类.另外,请确保使用 using 块来确保在完成连接后将其返回到连接池.另外,汤姆建议使用connectionstrings.com来为SqlConnection对象找出正确的连接字符串.

Use System.Data.SqlClient.SqlConnection, as well as SqlCommand and the rest, instead of the OleDb classes. Also be sure you use using blocks to ensure that your connection is returned to the connection pool when you're done with it. Also, Tom's suggestion of using connectionstrings.com to figure out the proper connection string for a SqlConnection object is a good one.

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
            }
        }
    }
}

这篇关于如何使用ADO.Net连接数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆