如何在C#中创建数据库

时间:2016-08-03 05:01:45

标签: c# mysql

这是我的代码:

private void btnSimpan_Click(object sender, EventArgs e)
    {
        Employees employees = new Employees();
        employees.EmployeeNumber = txtEmployeeNumber.Text;
        employees.LastName = txtLastName.Text;
        employees.FirstName = txtFirstName.Text;
        employees.Extension = txtExtension.Text;
        employees.Email = txtEmail.Text;
        employees.OfficeCode = cboOfficeCode.Text;

        if (employees.OfficeCode.CompareTo("1") == 0 || employees.OfficeCode.CompareTo("2") == 0 || employees.OfficeCode.CompareTo("3") == 0) employees.ReportsTo = "1143";
        else if (employees.OfficeCode.CompareTo("4") == 0 || employees.OfficeCode.CompareTo("5") == 0) employees.ReportsTo = "1102";
        else employees.ReportsTo = "1088";

        employees.JobTitle = "Sales Rep";

        try
        {
            stringBuilder = new StringBuilder();
            stringBuilder.Append(@"INSERT INTO employees (employeeNumber, lastName, firstName, extension, email, officeCode, reportsTo, jobTitle) VALUES (");
            stringBuilder.Append(employees.EmployeeNumber);
            stringBuilder.Append(", '");
            stringBuilder.Append(employees.LastName);
            stringBuilder.Append("', '");
            stringBuilder.Append(employees.FirstName);
            stringBuilder.Append("', '");
            stringBuilder.Append(employees.Extension);
            stringBuilder.Append("', '");
            stringBuilder.Append(employees.Email);
            stringBuilder.Append("', ");
            stringBuilder.Append(employees.OfficeCode);
            stringBuilder.Append(", '");
            stringBuilder.Append(employees.ReportsTo);
            stringBuilder.Append("', '");
            stringBuilder.Append(employees.JobTitle);
            stringBuilder.Append("')");

            comm = new MySqlCommand();
            comm.Connection = conn;
            comm.CommandText = stringBuilder.ToString();

            // Memakai ExecuteNonQuery, return n data yang terkena dampak
            int jmlDataTertambah = comm.ExecuteNonQuery();
            MessageBox.Show(jmlDataTertambah.ToString() + " data berhasil disimpan");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            this.Close();
        }
    }

2 个答案:

答案 0 :(得分:0)

public partial class frmMain : Form
{
    MySqlConnection conn = null;

    public frmMain()
    {
        InitializeComponent();
    }

    private void mnuConnect_Click(object sender, EventArgs e)
    {
        if (mnuConnect.Text.CompareTo("Connect") == 0)
        {
            String connString = @"Server=127.0.0.1;Database=product_sales_company;Uid=root;Pwd=;";

            try
            {
                conn = new MySqlConnection(connString);
                conn.Open(); // Membuka koneksi

                mnuEmployee.Enabled = true;
                mnuConnect.Text = "Disconnect";
                lblStatusKoneksi.Text = "Connected";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        else
        {
            if (conn != null)
            {
                conn.Close(); // Menutup koneksi
                conn.Dispose();
            }

            foreach (Form form in this.MdiChildren)
            {
                form.Close();
            }

            mnuEmployee.Enabled = false;
            mnuConnect.Text = "Connect";
            lblStatusKoneksi.Text = "Disconnected";
        }
    }

    private void mnuExit_Click(object sender, EventArgs e)
    {
        if (conn != null)
        {
            conn.Close(); // Menutup koneksi
            conn.Dispose();
        }
        Application.Exit();
    }

    private void mnuList_Click(object sender, EventArgs e)
    {
        // Cek apakah form yang memiliki jenis form yang sama (frmDaftarEmployee) sudah ada yang terbuka
        foreach (Form form in this.MdiChildren)
        {
            if (form.GetType() == typeof(frmDaftarEmployee))
            {
                form.Activate(); // Membuat form yang ditunjuk menjadi aktif
                return;
            }
        }

        frmDaftarEmployee formDafarEmployee = new frmDaftarEmployee(conn);
        formDafarEmployee.MdiParent = this;
        formDafarEmployee.Show();
    }
}
}

答案 1 :(得分:0)

要创建数据库,请使用以下创建命令:

  public void CreateDatabase(String createDb)
         {
             String connstr = ConfigurationManager.ConnectionStrings["Connstr"].ToString();
             MySqlConnection cnn = new MySqlConnection(connstr);

             try
             {
                 cnn.Open();
                 object result = string.Empty;
                 MySqlCommand Command = new MySqlCommand();
                 Command = cnn.CreateCommand();
                 Command.CommandType = CommandType.Text;
                 Command.CommandText = createDb;
                 Command = new MySqlCommand(Query, cnn);
                 //result = (object)NpgCommand.ExecuteScalar();
                 Command.ExecuteNonQuery();



             }
             catch (Exception er)
             {
                 String errorhere = er.Message;
                 if (cnn != null)
                 {
                     cnn.Close();
                 }


             }
             finally
             {
                 if (cnn != null)
                 {
                     cnn.Close();
                 }
             }

         }

然后调用form_load上的函数:

String createDb = "Create Database DBSample";
CreateDatabase(String createDb);

确保在app.config文件中设置连接字符串。

看起来像这样:

<configuration>
  <connectionStrings>
    <add name="Connstr" connectionString="data source=localhost;initial catalog=dbname;user=usename;password=password; default command timeout=120" />


      </connectionStrings>
  </configuration>
祝你好运