简体   繁体   中英

C# how to insert data to mysql using C#?

Im very new on C#

I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.

this my code Koneksi.cs

using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;



namespace timbangan
{
    public class Koneksi
    {
        public MySqlConnection konek;

        //string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
        string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";

        public void bukaKoneksi()
        {
            konek = new MySqlConnection(konfigKoneksi);
            konek.Open();

            var temp = konek.State.ToString();

            if (temp == "Open")
            {

                MessageBox.Show(@"Connection working.");

            }
            else {

                MessageBox.Show(@"Please check connection string");



            }
        }
        public void tutupKoneksi()
        {
            konek = new MySqlConnection(konfigKoneksi);
            konek.Close();
        }


    }//end of koneksi
}//end namespace

Isidata.cs File

using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

namespace timbangan
{
    public class Isidata
    {
        MySqlDataAdapter adapter;
        MySqlCommand komand;
        Koneksi classKoneksi;
        DataTable tabel;
        string sql = "";

        public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
        {
            classKoneksi = new Koneksi();

            sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
            //MessageBox.Show(sql);
            tabel = new DataTable();


            try
            {
                classKoneksi.bukaKoneksi();
                komand = new MySqlCommand(sql);
                adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
                adapter.Fill(tabel);
            }

            catch (Exception)
            {
                MessageBox.Show("error");
            }
            return tabel;
        }


    }//end of issdata
}//end of timbangan

Form1.cs File

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;

namespace timbangan
{
    public partial class Form1 : Form
    {
        public DataTable tabel;
        public string status = "";
        public string berat_filter, qty, nama_barang, dari, shift;


        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Isidata isi = new Isidata();
            tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
            MessageBox.Show("Berhasil");

        }


    }
}

Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?

Thanks in advance

You could redesign your classes to something like this

namespace timbangan
{
    public static class Koneksi
    {
        public static MySqlConnection konek;

        private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";

        public static MySqlConnection GetConnection()
        {
            konek = new MySqlConnection(konfigKoneksi);
            konek.Open();
        }
    }//end of koneksi

    public class Isidata
    {
        public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
        {
             sql = @"insert into tb_timbang
             (BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) 
             values (@berat_filter,@qty,@nama_barang,@dari,@shift)";
             try
             {
                 using(MySqlConnection cnn = Koneksi.GetConnection())
                 using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
                 {
                     cmd.Parameters.Add("@berat_filter", MySqlDbType.VarChar).Value = berat_filter;
                     cmd.Parameters.Add("@qty", MySqlDbType.VarChar).Value = qty;
                     cmd.Parameters.Add("@name_barang", MySqlDbType.VarChar).Value = nama_barang;
                     cmd.Parameters.Add("@dari", MySqlDbType.VarChar).Value = dari;
                     cmd.Parameters.Add("@shift", MySqlDbType.VarChar).Value = shift;
                     return cmd.ExecuteNonQuery();

                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("error " + ex.Message);
                     return -1;
                 }
             }
         }
     }//end of issdata
}//end of timbangan

In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections

The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class

As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum

Make a class named DBClass.cs and write the below code-

    class DBClass
        {
            MySqlCommand odcmd = new MySqlCommand();
            MySqlConnection odcon = new MySqlConnection();
            MySqlDataAdapter oda = new MySqlDataAdapter();

            public DBClass()
            {                

            }

public void OpenConnection()
        {
            odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
                if (odcon.State == ConnectionState.Closed)
                    odcon.Open();
                oda.SelectCommand = odcmd;
                odcmd.Connection = odcon;
        }

        public void CloseConnection()
        {
            if (odcon.State == ConnectionState.Open)
                odcon.Close();
        }

            public DataTable Select(string sql)
            {
                DataTable dt = new DataTable();
                odcmd.CommandText = sql;
                oda.Fill(dt);
                return dt;
            }

            public int ModiFy(string sql)
            {
                odcmd.CommandText = sql;
                return odcmd.ExecuteNonQuery();
            }
        }

On your form, Now you can fire your query like-

DbclassObject.Modify(Your_Insert_Update_Delete_Query);

DataTable dt= DbclassObject.Select(Your_Select_Query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM