C#与MySQL数据库相关

时间:2010-12-19 01:03:11

标签: c# mysql database

我想要实现的是从我的第一个表单自动将数据输入MySQL数据库。

现在,我只能在点击此表单时将数据输入数据库。如何在不单击每个表单的情况下保存数据,如何在第一个表单中自动保存所有数据?有人可以帮忙吗?

提前致谢。

        RegistryKey rk = Registry.CurrentUser;
        rk = rk.OpenSubKey("Software\\Microsoft\\Internet Explorer\\TypedURLs", false);
        PrintKeys(rk);
        rk.Close();

        void PrintKeys(RegistryKey rk)
        {
        if (rk == null)
        {
            richTextBoxBrowsing.Text = "Browsing history is empty!" + "\n";
            return;
        }

        richTextBoxBrowsing.AppendText("Subkeys of " + rk.Name + "\n");

        try
        {
            string[] valnames = rk.GetValueNames();

            foreach (string s in valnames)
            {
                //int i = richTextBoxBrowsing.SelectionStart;
                string val = (string)rk.GetValue(s);
                richTextBoxBrowsing.AppendText("-----------------------------------------------" + "\n");
                richTextBoxBrowsing.AppendText(s + "\n");
                richTextBoxBrowsing.AppendText(val + "\n");

                //create a MySQL connection with a query string
                MySqlConnection myConn = new MySqlConnection("user id=root; password=qwerty123456; database=syscrawl; server=localhost");

                //open the connection
                myConn.Open();

                MySqlCommand myCommand = myConn.CreateCommand();

                myCommand.CommandText =
                "insert into browsing_history (unique_id, url)"
                + " values "
                + "('" + s + "', '" + val + "')";

                MySqlDataReader myResult = myCommand.ExecuteReader();

                //close the connection
                myConn.Close();
            }
        }

        catch (Exception MyError)
        {
            richTextBoxBrowsing.AppendText("An error has occurred: " + MyError.Message + "\n");
        }
    }

1 个答案:

答案 0 :(得分:1)

嗯...某些背景可能会有所帮助。从您所说的内容来看,即使在您的表单上,发布的代码也会发生在onClick上?

如果您只是希望在表单加载时立即发生,请将代码放入窗体的onLoad事件中(双击窗体标题栏以转到onLoad事件)。

如果这还不够,请更详细/具体地说明您要做的事情。