C# 我可以公开 sqlConnection 并从其他形式引用它吗?
我的第一个表单上有一个 sqlConnection,想知道是否可以将其公开,以便我可以从其他表单中引用它。到目前为止我拥有的代码如下,但我不知道在哪里或如何公开它。
public partial class frmConnect : Form
{
public frmConnect()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
String server;
server = cmbConnect.SelectedItem.ToString();
MessageBox.Show(server);
sqlConnectionNW.ConnectionString = "Data Source=" + server + ";Initial Catalog=Northwind;Integrated Security=True";
try
{
sqlConnectionNW.Open();
MessageBox.Show("Successfully Connected!");
frmSignIn frmLogIn = new frmSignIn();
frmLogIn.server = server;
sqlConnectionNW.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
I have an sqlConnection on my first form and wondered if I could make it public so I could refer to it from other forms. The code I have so far is below, but I don't know where I would make it public or how.
public partial class frmConnect : Form
{
public frmConnect()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
String server;
server = cmbConnect.SelectedItem.ToString();
MessageBox.Show(server);
sqlConnectionNW.ConnectionString = "Data Source=" + server + ";Initial Catalog=Northwind;Integrated Security=True";
try
{
sqlConnectionNW.Open();
MessageBox.Show("Successfully Connected!");
frmSignIn frmLogIn = new frmSignIn();
frmLogIn.server = server;
sqlConnectionNW.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您的连接对象保存在类的字段或属性中。即使该领域或财产是私有的,这样做通常也不是一个好主意。
最佳实践是将连接保留为需要的局部变量。尽可能晚地打开它们并尽早关闭它们,最好将它们包装在
使用
块。I'm assuming that your connection object is being held in a field or property of the class. It's generally not a good idea to do that, even if the field or property is private.
Best practice is to keep your connections as local variables where they're needed. Open them as late as possible and close them as early as possible, preferably by wrapping them in a
using
block.您应该将连接和所有处理从表单中提取到它自己的类中——您可以将其称为 DataHandling。将其传递到表单中以及您想要使用它的任何位置。
:-)
You should extract the connection and all the handling out from the form into its own class -- you could call it DataHandling. Pass this into the form and whereever you want to use it.
:-)
我建议你不要这样做。为了访问数据库,最好使用它自己的类,您将拥有与数据库交互的所有方法(选择、插入、更新和删除查询)。每个方法都有自己的 SqlConnection 实例化(创建新对象)。
你可以这样做:
希望它有帮助,
米贾
I would suggest you not to do it this way. For accessing to the dataBase its best to use its own class, where you will have all the methods which will interact with the dataBase (select, insert, update and delete queries). And every single method will have its own SqlConnection instantiation (creation of the new object).
You can do it like:
Hope it helps,
Mitja