2015-10-06 156 views
1

我是初学者。在C#中连接到SQL Server的最佳方法WPF

我已经找到了一种方法使用下面的代码连接到SQL Server:

private void getListBtn_Click(object sender, RoutedEventArgs e) 
    { 
     SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=myDB;Integrated Security=true;"); 
     SqlDataAdapter sda = new SqlDataAdapter("SELECT ID,Date,Name,City FROM Info;", con); 
     DataTable dt = new DataTable(); 
     sda.Fill(dt); 
     dataGridForm.ItemsSource = dt.DefaultView; 

我也想从表中获取的行数,将其设置为一个标签,但它不是一个好主意复制并粘贴这段代码,我想有一个sqlconnection的方法,所以我不会一次又一次为每一个查询重写这段代码。

对不起,我是一个绝对的初学者,3天后,我开始学习C#WPF。

+0

如果您的应用程序不是重型数据库类型,请考虑使用LINQ-to-Sql。与ORM解决方案相比更轻量。 – cscmh99

回答

0

这与WPF无关,这是通用编码,即使我不认为这与.NET相关。

针对当前显示计数的问题,您不必再次拨打电话。您可以从数据表行数中获取计数。但是,我会建议几件事:

  1. 根据您的需要,您应该有一个或不同的单独的图层,如业务,数据访问等。
  2. 您不应按照您在此提供的方式提供连接。
  3. 您可以根据您的需要选择使用任何ORM,如实体框架,NHibernate等。这只是一个方向,您可以选择坚持使用ADO.Net,因为您有自己的选择。但我肯定会建议多投入一层,以避免重复代码和更加结构化的方法。
0

如果你不需要这么多的性能,最好的选择就是像实体框架那样的ORM。 Here是基本的东西。

只需使用它就像在MVC应用程序。

1

是的一些框架和/或ADO的解决方案是好的,也许是最好的“专业”的接近,你说你是一个初学者,我不是那么远;-)。

所以最简单的方法是为sql连接添加一个新类。在例子中添加一个Sqlconnect.cs类。

using System.Data.SqlClient; 

public class Sqlconnect 
{ 
    public SqlConnection Con { get; set; }//the object 
    private string conString { get; set; }//the string to store your connection parameters 
} 

这个类必须打开连接的方法和一个将其关闭。

public void conOpen() 
{ 
    conString = "Data Source=..."; //the same as you post in your post 
    Con = new SqlConnection(conString);// 
    try 
    { 
     Con.Open();//try to open the connection 
    } 
    catch (Exception ex) 
    { 
     //you do stuff if the connection can't open, returning a massagebox with the error, write the error in a log.txt file... 
    } 
} 
public void conClose() 
{ 
    Con.Close();//close the connection 
} 

在您需要sql查询的其他类中,您首先实例化一个新对象。

private void getListBtn_Click(object sender, RoutedEventArg e) 
{ 
    Sqlconnect con = new Sqlconnect();//instantiate a new object 'Con' from the class Sqlconnect.cs 
    con.conOpen();//method to open the connection. 

    //you should test if the connection is open or not 
    if(con!= null && con.State == ConnectionState.Open)//youtest if the object exist and if his state is open 
    { 
     //make your query 
     SqlDataAdapter sda = new SqlDataAdapter("your query", con); 
     //etc 

     con.conClose();//close your connection 
    } 
    else 
    { 
     //the connection failed so do some stuff, messagebox...as you want 
     return;//close the event 
    } 

} 

这个例子需要一些改进,很明显,但我写这样写得很清楚。