我如何称呼另一个班级的班级

我如何称呼另一个班级的班级

本文介绍了更新“我如何称呼另一个班级的班级”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接字符串类,我需要在另一个类中调用这个类,用于sql命令,用于将值插入带有存储过程的表中。



连接字符串的第一类代码:



I have a class for connection string and i need to call this class in another class for a sql command for insert a value into a table with a stored procedure.

Code for the first class for connection string:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace GestiuneP
{
    class Conectare
    {
        public static SqlConnection con = null;

        public static void Conexiune()
        {
            con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Vali&Aurelian\Documents\GestiuneP.mdf;Integrated Security=True;Connect Timeout=30");
            con.Open();
        }
    }
}







和第二堂课用于sql命令,用于将值插入带有存储过程的表中






and the second class for a sql command for insert a value into a table with a stored procedure

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace GestiuneP
{

    class Adauga_Angajat
    {
        Conectare NewConnection = new Conectare();
        NewConnection.Conexiune();// here is the error: "GestiuneP.Adauga_Angajat.NewConnection is a field but is used like a type"
        SqlCommand myCommand = new SqlCommand("dbo.[sp_adauga_client]", con);
        myCommand.CommandType = CommandType.StoredProcedure;


    }
}

推荐答案

class Conectare
{
    public static SqlConnection con = null;

    public void Conexiune() // static is removed
    {
        con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Vali&Aurelian\Documents\GestiuneP.mdf;Integrated Security=True;Connect Timeout=30");
        con.Open();
    }
}






or

//Conectare NewConnection = new Conectare();
Conectare.Conexiune();// Class name used



我个人更喜欢第二个这种情况。



作为旁注,您似乎将SqlConnection存储了一段时间,这是单个操作所需的。如果是这种情况,我建议不要这样做。相反,当您需要连接时,创建并打开它,执行SQL命令,最后正确关闭连接。


Personally I would prefer the second one in this situation.

As a side note, you seem to store the SqlConnection for a longer period of time that is needed for a single operation. If that is the case, I would suggest not doing so. Instead, when you need the connection, create and open it, execute the SQL commands and at the end close the connection properly.


这篇关于更新“我如何称呼另一个班级的班级”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:12