c# - 在 C# WPF 中连接到 SQL Server 的最佳方法

标签 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 的方法,所以我不会重写这个为每个查询一次又一次地编码。

抱歉,我是一个绝对的初学者,自从我开始学习 C# WPF 已经 3 天了。

最佳答案

是的,一些框架和/或 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
    }

}

这个例子需要一些改进,这是显而易见的,但我这样写是为了最清楚。

关于c# - 在 C# WPF 中连接到 SQL Server 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32977270/

相关文章:

c# - 对不同长度的二维数组进行排序

c# - 遍历子元素,找到一些东西并访问它的兄弟属性

c# - DateTime 解析失败 24 :00:00 in the HH:mm:ss format

wpf - 如何结合我看似多余的 XAML

c# - FindAsync - 数据库 'master' 中的 CREATE DATABASE 权限被拒绝

sql - TSQL 选择删除

sql - 如何查找末尾带有特殊字符的列数据

sql-server - 查找 2 个日期之间的星期一

wpf - 堆栈面板中的垂直滚动

wpf - 通过 MVVM RelayCommand 从 ListBox 中删除 SelectedItems