gpt4 book ai didi

c# - 当我将 MySqlConnection 放在其他类中并从其他表单调用它时,如何创建 MySqlCommand

转载 作者:行者123 更新时间:2023-11-29 21:42:37 26 4
gpt4 key购买 nike

优秀的程序员。任何人都可以用 c# 帮助我。每当我想插入或执行任何查询时,如何从其他表单调用此类。

这是我的名为 DBConnection 的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication2
{
class DBConnector
{
private MySqlConnection con;
private String server;
private String db;
private String uid;
private String password;

public DBConnector()
{
Initialize();
}

private void Initialize()
{
server = "localhost";
db = "test";
uid = "root";
password = "";
String connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
db + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

con = new MySqlConnection(connectionString);
}

public void DatabaseConnector()
{
server = "localhost";
db = "test";
uid = "root";
password = "";
String connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
db + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

con = new MySqlConnection(connectionString);
}
public void OpenCon()
{
con.Open();
}
public void CloseCon()
{
con.Close();
}

}
}

每当我按下按钮时,这是我的表单按钮类。然后就会查询。我的问题是如何调用 con = new MySqlConnection(connectionString); 来创建 MySqlCommand。请帮忙。我很困惑。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication2
{
public partial class FrmAdd : Form
{

public FrmAdd()
{
InitializeComponent();
}

private void FrmAdd_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{

var mycon = new DBConnector();

try
{
mycon.OpenCon();
MessageBox.Show("Well done!");
}
catch (MySqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}


string query = "INSERT INTO info values (1,'John','Mac','P',21)";



}
}
}

最佳答案

为了访问另一个类中的MySqlConnection对象,您需要将DbConnector类标记为internalpublic,即它应该变成:

public class DbConnector{
...
}

您还需要在属性本身上设置访问修饰符并添加 getter,如下所示:

public MySqlConnection con { get; }

然后,在实例化 DbConnector 后的 FrmAdd 中,您可以使用数据库对象,例如 mycon.con.SomeMethod()

另外,为什么有两个方法 DatabaseConnector()Initialize() 如果它们做同样的事情?

关于c# - 当我将 MySqlConnection 放在其他类中并从其他表单调用它时,如何创建 MySqlCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34377248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com