从app.config读取的connectionstring的类的用法 [英] usage of classes for my connectionstring that reads from app.config

查看:43
本文介绍了从app.config读取的connectionstring的类的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在app.config中创建一个ConnectionString,我试图通过我创建的类初始化它。



App.config:



 < ?xml version =   1.0 encoding =   utf-8>  
<配置>
< startup>
< supportedRuntime version = v4.0 sku = 。NETFramework,Version = v4.5 />
< / startup >
< connectionStrings>
< add name = EQCas
connectionString = 数据源= solutionworx-pc\sqlexpress;初始目录= eqcas;集成安全性=真; />
< / connectionStrings >
< / configuration >





申请:



 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Configuration;
使用 System.Data.SqlClient;

命名空间 ConsoleApplication1
{
class 计划
{
静态 void Main( string [] args)
{
new SQLConnect();
SqlDataReader myReader = null ;
SqlCommand myCommand = new SqlCommand( select x_id,fullname,email FROM cas_user_ext WHERE fullname = @fullname);
myCommand.Parameters.AddWithValue( @ username Ivan Lubbe);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader [ x_id]);
Console.WriteLine(myReader [ fullname]);
Console.WriteLine(myReader [ email]);
}
}
}
}

public SQLConnect
{
public string myConnection;

public SQLConnect()
{
myConnection = ConfigurationManager.ConnectionStrings [ EQCas]。ConnectionString;
SqlConnection connectSQL = new SqlConnection(myConnection);
connectSQL.Open();
}
}





我假设我使用的是我创建错误的类。大多数教程都不清楚如何使用

类,因为我试图使用它。我是C#的新手,现在已经使用了大约4个星期。非常感谢任何帮助。此外,一旦我的连接字符串工作,我将尝试创建一个类来从SQL获取/设置值不同于上面的代码(仅用于测试目的)



这个是我已经完成了我得到的建议。



v2



 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Configuration;
使用 System.Data.SqlClient;

命名空间 ConsoleApplication1
{
class 计划
{
静态 void Main( string [] args)
{
SQLConnect sqlcon = new SQLConnect();
SqlDataReader myReader = null ;
SqlCommand myCommand = new SqlCommand( select x_id,fullname,email FROM cas_user_ext WHERE fullname = @fullname
sqlcon.Connection);
myCommand.Parameters.AddWithValue( @ fullname Ivan Lubbe);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader [ x_id]);
Console.WriteLine(myReader [ fullname]);
Console.WriteLine(myReader [ email]);
}
sqlcon.Close();
}
}
}

public class SQLConnect
{
public string myConnection;
public SqlConnection Connection { get ; private set ; }

public SQLConnect()
{
myConnection = ConfigurationManager.ConnectionStrings [ EQCas]。ConnectionString;
// SqlConnection connectSQL = new SqlConnection(myConnection);
// connectSQL.Open();
Connection = new SqlConnection(myConnection);
Connection.Open();
}

内部 void 关闭()
{
Connection.Close();
}
}





还有什么我应该改进的吗?或者我应该阅读的具体内容是什么?

解决方案

嗯...我觉得你需要一些练习...



您创建了该类的新实例:

  new  SQLConnect (); 

但是你没有提到它:就像在商店买一包糖果,当你离开时把它们留在后面:当你回到家时,你不能吃任何甜心,因为你不再拥有你买的实例。



所以从保留参考开始:

 SqlConnect con =  new  SQLConnect(); 





但是......你没有保留你在课堂上创建的SqlConnection!所以,当你退出构造函数时,再一次你无法得到甜心! :笑:

所以添加一个Property以允许你检索它:

  public   class  SQLConnect 
{
private 字符串 myConnection;
public SqlConnection Connection { get ; private set ; }

public SQLConnect()
{
myConnection = ConfigurationManager.ConnectionStrings [ EQCas]。ConnectionString;
Connection = new SqlConnection(myConnection);
Connection.Open();
}
}

现在,连接将持续与您的类的引用一样长。



现在,你需要将命令附加到Connection或者SqlCommand不知道它应该在哪里执行:

 SqlCommand myCommand =  new  SqlCommand(  select x_id,fullname,email FROM cas_user_ext WHERE fullname = @fullname,con.Connection); 





这不是最佳解决方案:它不允许关闭连接(你需要做什么) )或处置它(你也需要这样做)



我可能会采用不同的方式:在我的班级中有一个静态方法(或属性)返回连接字符串,让外部代码直接创建,打开,使用和处理SqlConnection对象。



Typos - OriginalGriff [/ edit]


你没有将连接对象传递给sqlcommand



替换你的主要功能



static void Main(string [] args)

{

SQLConnect sq = new SQLConnect();

SqlConnection con = new Sqlconnection (sq.myConnection);

con.Open();

SqlDataReader myReader = null;

SqlCommand myCommand = new SqlCommand(select x_id ,全名,电子邮件FROM cas_user_ext WHERE fu llname = @fullname,con);

myCommand.Parameters.AddWithValue(@ username,Ivan Lubbe);

myReader = myCommand.ExecuteReader();

while(myReader.Read())

{

控制台.WriteLine(myReader [x_id]);

Console.WriteLine(myReader [fullname]);

Console.WriteLine(myReader [email]) ;

}

con.Close();

}


I have tried to create a ConnectionString within my app.config and i'm trying to initialize it via a class i have created.

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <connectionStrings>
    <add name="EQCas"
         connectionString="Data Source=solutionworx-pc\sqlexpress;Initial Catalog=eqcas;Integrated Security=True;"/>
  </connectionStrings>
</configuration>



Application:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new SQLConnect();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select x_id, fullname, email FROM cas_user_ext WHERE fullname = @fullname");
            myCommand.Parameters.AddWithValue("@username", "Ivan Lubbe");                                          
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                Console.WriteLine(myReader["x_id"]);
                Console.WriteLine(myReader["fullname"]);
                Console.WriteLine(myReader["email"]);
            } 
        }
    }
}

public class SQLConnect
{
    public string myConnection;

    public SQLConnect()
    {
        myConnection = ConfigurationManager.ConnectionStrings["EQCas"].ConnectionString;
        SqlConnection connectSQL = new SqlConnection(myConnection);
        connectSQL.Open();
    }
}



I assume i am using the class i created wrong. Most tutorials are not very clear on how to use
classes as i have tried to use it. I am new to C# been using it for around 4 weeks now. Would appreciate any assistance. Also once i have got my connection string working i will attempt to create a class to get/set values from SQL unlike the code above (just for testing purposes)

This is what i have done with the advice i have gotten.

v2

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SQLConnect sqlcon = new SQLConnect();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select x_id, fullname, email FROM cas_user_ext WHERE fullname = @fullname", 
                                                                                    sqlcon.Connection);
            myCommand.Parameters.AddWithValue("@fullname", "Ivan Lubbe");                                          
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                Console.WriteLine(myReader["x_id"]);
                Console.WriteLine(myReader["fullname"]);
                Console.WriteLine(myReader["email"]);
            } 
        sqlcon.Close();
        }
    }
}

public class SQLConnect
{
    public string myConnection;
    public SqlConnection Connection { get; private set; }

    public SQLConnect()
    {
        myConnection = ConfigurationManager.ConnectionStrings["EQCas"].ConnectionString;
        //SqlConnection connectSQL = new SqlConnection(myConnection);
        //connectSQL.Open();
        Connection = new SqlConnection(myConnection);
        Connection.Open();
    }

    internal void Close()
    {
        Connection.Close();
    }
}



Anything else that i should improve on? Or specific things i should read up on?

解决方案

Um...I think you need a bit of practice at this...

You create a new instance of the class:

new SQLConnect();

But you don't keep a reference to it: that's like buying a packet of sweets in a shop and leaving them behind when you leave: when you get home, you can't eat any of the sweeties because you no longer have the instance you bought.

So start by keeping the reference:

SqlConnect con = new SQLConnect();



But...you don't keep the SqlConnection you create within your class either! So when you exit the constructor, once again you can't get at the sweeties! :laugh:
So add a Property to allow you to retrieve it:

public class SQLConnect
{
    private string myConnection;
    public SqlConnection Connection { get; private set; }

    public SQLConnect()
    {
        myConnection = ConfigurationManager.ConnectionStrings["EQCas"].ConnectionString;
        Connection = new SqlConnection(myConnection);
        Connection.Open();
    }
}

Now, the connection will last as long as the reference to your class does.

Now, you need to "attach" the Command to the Connection or the SqlCommand doesn't know where it is supposed to execute:

SqlCommand myCommand = new SqlCommand("select x_id, fullname, email FROM cas_user_ext WHERE fullname = @fullname", con.Connection);



This isn't an optimal solution: It doesn't allow for closing the connection (which you need to do) or Disposing of it (which you also need to do)

I'd probably do it differently: have a static method (or property) in my class which returned the connection string, and let the external code create, open, use and Dispose the SqlConnection object directly.

[edit]Typos - OriginalGriff[/edit]


You have not pass the connection object to sqlcommand

replace your main function

static void Main(string[] args)
{
SQLConnect sq=new SQLConnect();
SqlConnection con=new Sqlconnection(sq.myConnection);
con.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select x_id, fullname, email FROM cas_user_ext WHERE fullname = @fullname",con);
myCommand.Parameters.AddWithValue("@username", "Ivan Lubbe");
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["x_id"]);
Console.WriteLine(myReader["fullname"]);
Console.WriteLine(myReader["email"]);
}
con.Close();
}


这篇关于从app.config读取的connectionstring的类的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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