如何将web服务db Connection.vba更改为c#代码?

时间:2011-06-03 01:59:32

标签: c# web-services sqlconnection

我是c#中的新人,我必须在c#中编写网络服务(btw business to business)

但我通常在vb中做,所以我不确定它在C#dbconnection中的样子 。如果可以告诉我一些链接,这将有助于我做网络服务(顺便说一句企业对企业) 现在我已将服务器中的sql数据库连接到Web服务 这是我的dbconnection.vb,所以如何将其更改为c sharp,希望有人能告诉我c#中的代码是什么样的

    Imports Microsoft.VisualBasic
Imports System.Data.SqlClient

Public Class dbconnection
    Function getConnection() As SqlConnection
        Dim dbConn As SqlConnection

        dbConn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|delivery.mdf;Integrated Security=True;User Instance=True")

        Return dbConn
    End Function
End Class

1 个答案:

答案 0 :(得分:0)

一对一实现如下:

using System.Data.SqlClient;
public class DbConnection
{
    public SqlConnection getConnection()
    {
        SqlConnection dbConn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|delivery.mdf;Integrated Security=True;User Instance=True");
        return dbConn;
    }
}

但是,我不能说它符合最佳做法。考虑实施IDisposable以正确释放非托管资源:

using System.Data.SqlClient;
using System;
public class DbConnection : IDisposable
{
    public SqlConnection DbConn { get; private set; }

    public DbConnection()
    {
        DbConn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|delivery.mdf;Integrated Security=True;User Instance=True");
    }

    public void Dispose()
    {
        if (DbConn.State != System.Data.ConnectionState.Closed) {
            DbConn.Close();
        }
        DbConn.Dispose();
    }
}

它的用法类似于

using(DbConnection myClassInstance = new DbConnection()) {
    SqlConnection connection = myClassInstance.DbConn;
}