应用程序中的通用连接路径 [英] Connection Path Universal in application
问题描述
亲爱的所有人,
在与SQL Server的连接过程中,可以从已经定义的连接中与数据库连接.即
正如我已在类中定义以下提及的连接并在所有地方使用此连接类,而不是定义所有
返回服务器=.\ SQLEXPRESS; AttachDbFilename = F:\ jatin \ sale \ jatin_Data.MDF;集成安全性= True;连接超时= 30;用户实例= True"
现在我的问题是我可以在数据集或Crystal报表中使用此连接,以避免在每个位置出现所有连接定义问题.
亲切地指导我.
Dear All,
During the connection with SQL server could be connect with database from the already define connection. i.e
As I have define the under mention connection in a class & use this connection class at all place instead of defining all
Return "server=.\SQLEXPRESS;AttachDbFilename=F:\jatin\sale\jatin_Data.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"
Now my question is could I use this connection in the Dataset or in Crystal report to avoid all connection defination at every place.
KIndly guide me.
推荐答案
是的.由于OOP的可重用性原理,它很有可能实现.
.NET提供了ref
关键字,您可以执行此操作..我将在C#中编写一个代码示例,该示例将说明与您的问题有关的用法..
yeah..its very possible thanks to re-usability principle of OOP.
.NET has come up with theref
keyword which allows you to do this very thing..I''ll put up a code sample in C# which will illustrate the usage of it in relation to your question..
.
.
/* This class contains the Connection String, connection and command object info */
static class DB_Conn
{
public static void Connection(ref SqlConnection conn, ref SqlCommand cmd)
{
conn = new SqlConnection();
conn.ConnectionString = "[Input Connection String here]";
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure; // or Text / Table
}
}
现在,在另一个类中使用它,而不必再次创建所有内容..
Now using it in a different class without having to create everything again..
.
.
class UseData
{
/* Now this next step is very important in order to ensure re-usability
Declare a connection and command object */
SqlConnection conn; /* you can set them to null if you want*/
SqlCommand cmd;
/* So to use it in a member method like below..*/
Public void deleteData(ref Conn, ref Cmd)
{
/*Now just call the method in the 1st class and pass the connection objects in your argument list to it */
DB_Conn.Connection(Conn,Cmd);
/* and it will set up all the connection and command objects just as was done in the method */
cmd.CommandText="[Input stored Procedure/Query string here]";
conn.Open();
cmd.ExecuteNonQuery();
if(Conn.State == ConnectionState.Open)
{
Conn.Close();
}
cmd.Dispose();
/* This is optional but for performance reasons and good programming practice, I manually do my garbage collection */
}
}
而且您的程序应该运行顺利..
如果您喜欢上述内容,请接受答案并投票..:)
And your program should run smoothly..
If you love the above, accept answer and give it a vote..:)
这篇关于应用程序中的通用连接路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!