1

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

Uchsun
  • 361
  • 1
  • 8
  • 25
  • insert query does not work with DataAdapter, rather you should use ExecuteNonQuery() function. – Prateek Shukla Aug 06 '15 at 06:43
  • DataAdapter.Fill works FIRST with a SELECT query to retrieve data from a database then (if you have a single table SELECT with a primary key available) you could add a custom MySqlCommand with an INSERT query related to your retrieved data and call DataAdapter.Update to add your new data to the database. In your scenario I would simply use the MySqlCommand with ExecuteNonQuery and DO NOT FORGET to use the appropriate parameters instead of string concatenation – Steve Aug 06 '15 at 06:56

2 Answers2

1

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

Steve
  • 213,761
  • 22
  • 232
  • 286
0

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);
Prateek Shukla
  • 593
  • 2
  • 7
  • 27
  • Sory im ask again, is fire my query on button save like this DbclassObject.Modify(insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')); – Uchsun Aug 06 '15 at 07:11
  • This code leads to memory leaks of big impact. Please do not do this. Connections should be closed and disposed as soon as possible – Steve Aug 06 '15 at 07:21
  • Yes you need to call it on save button click.. by the way Steve, it's just a sample code one should or can connection close directly – Prateek Shukla Aug 06 '15 at 07:25
  • This is still plain wrong. You made a class that opens the connection and you expect someone else to close it? By the way, this class doesn't address the other big problem in the OP code. [Sql Injection](http://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work), I am sorry but a do-it-all class for database access is always a bad idea – Steve Aug 06 '15 at 07:29
  • Steve, the code is modified and the open and close connection is added. – Prateek Shukla Aug 06 '15 at 07:40
  • Oke @steve , which code should I use? and Please give me sample to use ExecuteNonQuery() and where to put mysql query. I'm still not understand. – Uchsun Aug 06 '15 at 07:47