c来自功能的锐利回归物体

时间:2012-12-28 19:39:25

标签: c# mysql database

我正面临一个问题,当我创建自己的类时,我想创建Mysql连接函数,我想在我的所有表单中使用它我这样做

program.cs

using MySql.Data.MySqlClient;
using MySql.Data.Types;
using System.Xml;
using System.IO;
public class testing
    {
        public string fahadt="Hello Class";




        public  void conncting()
        {


            MySqlConnection connection;
            string cs = @"server=localhost;userid=root;password=;database=taxi";
            connection = new MySqlConnection(cs);
            try
            {

                connection.Open();

            }
            catch (MySqlException ex)
            {
               // MessageBox.Show(ex.ToString());
            }

        }

    }

以我的形式

private void button7_Click(object sender, EventArgs e)
        {
            testing fahad = new testing();
            try
            {
                dataGridView1.Show();
                fahad.conncting();

                // here is error under fahad.conncting.createcommand();
                MySqlCommand cmd = fahad.conncting.CreateCommand();
                //cmd.CommandText = "SELECT * FROM  ocms_visitors WHERE `id`='"+textBox4.Text+"'";
               // MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
                //textBox4.Text = adap.id;

               // DataSet ds = new DataSet();
               // adap.Fill(ds);

               // dataGridView1.DataSource = ds.Tables[0].DefaultView;
                //MessageBox.Show("Yes Mysql Connection is Working Now  !");
            }
            catch (Exception)
            {
                throw;
            }

        }

我不知道我怎么能做到这一点非常新= C#

请帮助我,我还有另外一个q我应该使用 在班级和形式中使用......还是在课堂上足够?

感谢

3 个答案:

答案 0 :(得分:2)

您需要返回MySqlConnection

将您的功能修改为:

    public  MySqlConnection conncting()
    {


        MySqlConnection connection;
        string cs = @"server=localhost;userid=root;password=;database=taxi";
        connection = new MySqlConnection(cs);
        try
        {

            connection.Open();
            return connection;

        }
        catch (MySqlException ex)
        {
            return null;
           // MessageBox.Show(ex.ToString());
        }

    }

答案 1 :(得分:0)

要回答您的初始问题,我认为您已经创建了您正在寻找的连接。接下来的步骤将是了解SqlCommand类。

有关参考/启发,请尝试此link,并快乐编码!

答案 2 :(得分:0)

我怀疑您想要从conncting()方法返回连接?

    public MySqlConnection conncting()
    {
        string cs = @"server=localhost;userid=root;password=;database=taxi";
        MySqlConnection connection = new MySqlConnection(cs);
        connection.Open();
        return connection;
    }

要回答第二个问题,是的,尽可能使用using {..}块对IDisposable个实例是一个好主意。这包括连接,命令,数据适配器等。以下可能是合理的模式:

    using (MySqlConnection conn = fahad.conncting())
    using (MySqlCommand cmd = new MySqlCommand("select * from table", conn))
    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
    using (DataTable dt = new DataTable())
    {
        da.Fill(dt);
        // do something with datatable
    }