使用c#在单独的类文件中进行SQL连接 [英] sql connection in seperate class file using c#

查看:126
本文介绍了使用c#在单独的类文件中进行SQL连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlConnection con = new SqlConnection("Server=server_name;Database=database_name;uid=userid;password=password");
con.Open();





我想创建一个单独的class.cs文件,并且可以在需要时调用此类它将帮助我不要在每个地方更改用户ID和密码只需在类文件中更改它并完成如何执行此操作。实际上我创建了文件,但问题是如何在sqlcommand位置使用con对象。该类必须返回con.or这样的东西。



I want to make a seperate class.cs file and can call this class whenever needed it will help me not to change userid and password in every place just change it in class file and its done how to do this.actually i have created the file but the problm is this how to use con object at the place of sqlcommand..the class must return con.or sumthing like that.

推荐答案

查看我的文章 http://www.codeproject.com/KB/tips/SqlParameters.aspx [ ^ ]

,其中包含用于连接数据库的通用类。
see my article http://www.codeproject.com/KB/tips/SqlParameters.aspx[^]
which holds classes for generic use in connecting to a database.


for例如,您可以创建一个新类:sqlParms.cs



然后在该类中,您可以创建任何您想要的功能,具体取决于您要对其进行操作的级别:简单的情况你可以创建一个名为getConn的函数,它返回连接字符串并调用它:



for example you can make a new class : sqlParms.cs

then in that class you can create any function you want depending on the level you want to work on it : in simple cases you can create a function called getConn which return the connection string and the call it like that :

sqlParms prms=new sqlParms();
SqlConnection con=prms.getConn();





这是一种简单的方法。其他你可以通过使用digimanus链接做更复杂的工作...

问候



this is the simple way. other you can do more complicated work by using digimanus link ...
regards


尝试

Try
using System.Data.SqlClient;

class myConnection
    {
        public static SqlConnection GetConnection()
        {
            string str = "Data Source=.;Initial Catalog = YourDatabaseName;uid =sa;pwd = YourPassword";

            SqlConnection con = new SqlConnection(str);
            con.Open();
            return con;
        }
    }


这篇关于使用c#在单独的类文件中进行SQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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