简体   繁体   English

C#如何使用C#将数据插入mysql?

[英]C# how to insert data to mysql using C#?

Im very new on C# 我在C#上很新

I Only create 1 Form that Can insert Data to Mysql Database. 我只创建1个可以将数据插入Mysql数据库的表单。 My code not have Error, but data cant enter the Database. 我的代码没有错误,但是数据无法进入数据库。 I m so confused. 我很混乱。

this my code Koneksi.cs 这是我的代码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 Isidata.cs文件

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 Form1.cs文件

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). 可以完全删除相同的Koneski类,并且可以在现场创建MySqlConnection(从配置文件等外部源读取连接Koneski )。 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 有一个ADO.NET 连接池基础结构(链接用于Sql Server,但对于MySql是相同的),可以非常有效地运行以处理您的连接

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. 重要的是Using语句 (在不再需要释放宝贵的资源时关闭并释放命令和连接),以及用于填充发送给服务器的命令的参数。 If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class 如果您需要在工作的其他方面使用适配器,则可以在Isidata类中添加其他类似方法

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 这对于日期时间字段尤为重要,当将日期时间字段视为字符串时,可能会让人头疼,无法正常工作。 请参见MySqlDbType枚举

Make a class named DBClass.cs and write the below code- 创建一个名为DBClass.cs的类,并编写以下代码-

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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