【问题标题】:Is there a better way to connect my DB to my Form?有没有更好的方法将我的数据库连接到我的表单?
【发布时间】:2018-11-21 01:16:45
【问题描述】:

我正在尝试将我的数据库连接到我的ListView,并且我正在尝试找到比书中介绍的更好的方法。我查看了几个论坛,其中很多都与下面我的代码中的内容相同。

我们没有太多时间在课堂上复习数据库,所以我对连接字符串的很多知识都来自互联网和书中的一小章。
我的数据库名称是GameStoreLibrary .

using System.Data;
using System.Data.SqlServerCe;

public partial class DisplayGameStoreTable : Form
{
    //WHAT THE C# FORUMS SAY TO DO
    public SqlCeConnection cn = new SqlCeConnection(@"
           Data Source=.;
           Initial Catalog=DB GameStoreLibrary;
           Integrated Security=True;
           MultipleActiveResultSets=True");

private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
    try
    {
        cn.Open();
    }

    catch(SqlCeException ex)
    {
        MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        Application.ExitThread();
    }
 }

private void NewGameBttn_Click(object sender, EventArgs e)
{
    listView1.Items.Clear();
    SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);

    try
    {
        SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
        DataTable dt = new DataTable();
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
            item.SubItems.Add(dr["releasedate"].ToString());
            item.SubItems.Add(dr["console"].ToString());
            item.SubItems.Add(dr["company"].ToString());
            item.SubItems.Add(dr["gameprice"].ToString());
            item.SubItems.Add(dr["quantity"].ToString());
        }
    }

    catch(Exception ex)
    {
        MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

【问题讨论】:

  • 了解 MVVM。
  • 你是指 WPF 还是 WinForms?
  • 那不是 WPF...
  • 哎呀,我的意思是 WinForms,我很抱歉
  • 不要尝试在整个班级中重复使用相同的连接对象。为每个查询创建并处置一个新对象,并且只共享连接字符串。由于有一个称为连接池的功能,因此效果更好。

标签: c# winforms sql-server-ce


【解决方案1】:

小提示:

尝试使用DBConnect 类,而不是每次都输入连接字符串并关闭连接。

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

namespace InventoryManagementSystem
{
    class DBConnect : IDisposable
    {


        private static String connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Private\InventoryManagementSystem\InventoryManagementSystem\InventoryDB.mdf;Integrated Security=True";
        public SqlConnection con = new SqlConnection(connectionString);

        public DBConnect()
        {
            try
            {
                con.Open();
                Console.WriteLine("Database connected");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine("Database Connection Failed");
                throw new Exception();
            }
        }

        public void Dispose()
        {
            con.Close();
        }
    }
}

在您的项目中拥有这个之后,您只需在想要访问数据库时创建一个对象。

public void getData(){

    using(DBConnect db = new DBConnect()){
        String q = "select * from TestTable";
        SqlCommand cmd = new SqlCommand(q,db.con);
        SqlDatareader r = cmd.ExcecuteReader();

    }
}

这也会自动关闭连接。

【讨论】:

    【解决方案2】:

    为了补充 Gihan 的答案,创建 App.Config 文件并将连接字符串放入其中也是一种公认​​的做法,因此它不在您的源代码中。这样就更容易更改而无需重新编译任何东西。

    使用 App.Config 的 ConnectionStrings 部分,然后您可以使用代码获取连接字符串:

    System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 2018-05-12
      • 2021-01-03
      • 2016-07-17
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多