c# - 有没有更好的方法将我的数据库连接到我的表单?
问题描述
我正在尝试将我的数据库连接到我的数据库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);
}
}
解决方案
为了补充 Gihan 的答案,创建 App.Config 文件并将连接字符串放在其中也是一种公认的做法,因此它不在您的源代码中。然后更容易更改而无需重新编译任何东西。
使用 App.Config 的 ConnectionStrings 部分,然后您可以使用代码获取连接字符串:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
推荐阅读
- php - 在 WordPress 中从我的数据库中检索数据的问题
- python - 如何按最大数字对数组进行排序
- java - 这个数组发生了什么?
- python - 将带有时间戳的excel文件转换为python日期和时间
- javascript - 寻求帮助解释一个大的组合算法
- hibernate - 异常:上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.BeanCreationException:
- vue.js - 如何在不重新渲染 html 的情况下切换 vue.js 路由器视图
- angular - 使用 Typescript 从 Angular 6 的在线链接中显示 Pdf
- windows - 尝试制作新的 vmswitch 时出现 hyper-v 通用故障
- powerbi - 用于计算列总数的 Power BI 条形图