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

时间:2015-12-20 01:52:39

标签: c# mysql class visual-studio-2013

优秀的程序员。任何人都可以帮我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)";



        }
    }
}

0 个答案:

没有答案