首页 > 解决方案 > 有没有更好的方法将我的数据库连接到我的表单?

问题描述

我正在尝试将我的数据库连接到我的数据库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);
    }
}

标签: c#winformssql-server-ce

解决方案


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

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

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


推荐阅读