0

我正在用 C# 开发一系列重用相同 SQL 代码的进程。下面是我为与我的测试数据库的 SQL 连接创建的类的示例。问题:如何在我的过程中调用类?我尝试了几件事,但是出现以下错误

错误:

SQLHelperCode.FirstConnect is a 'type'  which is not valid in the given context.
Only Assignment, call, increment, decrement and new object expressions can be used as a statement

FirstConnect 类

public class FirstConnect
{
    public FirstConnect()
    {
        SqlConnection conn;
        string path = @"C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data";
        const string dbName = "datadetail";
        {
            conn = new SqlConnection("user id=TestUser;" +
                                     "server=TestData\\SQLEXPRESS;" +
                                     "Trusted_Connection=yes;" +
                                     "connection timeout=30");

            try
            {
                conn.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

想在这段代码中调用 FirstConnect:

protected override void OnBarUpdate()
{
    accountName = Account.Name.ToString();

    if (accountName == 'Test1234')
    {
        //Call FirstConnect here.
    }
}
4

3 回答 3

5

这一行定义了类

public class FirstConnect
 {

这一行定义了构造函数

    public FirstConnect()
      {

下面将定义一个FirstConnect类型的变量,然后调用构造函数来创建它(我做了两行显式)

FirstConnect fc;
fc  = new FirstConnect();

通常你会想要有一个方法可以对对象做一些实际的事情

例如

SomeOtherObject varaibleName = fc.GetSomeData(accountName);
于 2012-05-25T17:01:56.247 回答
1

不是答案,只是一个很大的评论......

当使用实现IDisposable类似的类时SqlConnection,它们应该像这样使用:

using (var conn = new SqlConnection("user id=TestUser;server=TestData\\SQLEXPRESS;Trusted_Connection=yes;connection timeout=30"))
{
   //... do work ... 
}
于 2012-05-25T17:07:37.607 回答
1

FirstConnect fc = new FirstConnect();

于 2012-05-25T17:00:50.340 回答