简体   繁体   English

C#Mysql插入数据不起作用

[英]C# Mysql Insert Data not work

I am Nubie in C#, I Try to learn CRUD. 我是C#中的Nubie,尝试学习CRUD。 Select data Succes but I cant Save data to mysql. 选择数据成功,但是我无法将数据保存到mysql。 my table 我的桌子

mahasiswa

   ID| namae | jurusan | email
  _____________________________
  1 |  Bill  | IT      | bill@gmail.com
  2 | Tony   | IT      | Tony@gmail.com

ID is set to auto increment in Mysql 在MySQL中将ID设置为自动递增

and this my script for btn save 这是我的btn脚本保存

 void btnsave_Click(object sender, EventArgs e)
        {
            try 
            {
                if (txtid.Text != "" && txtnama.Text != "" && txtjurusan.Text != "" && txtemail.Text != "")
                {
                    query = string.Format("INSERT INTO mahasiswa values ('{1}','{2}','{3}');", txtnama.Text, txtjurusan.Text, txtemail.Text);

                    koneksi.Open();
                    perintah = new MySqlCommand(query, koneksi);
                    adapter = new MySqlDataAdapter(perintah);
                    int res = perintah.ExecuteNonQuery();
                    koneksi.Close();

                    if (res == 1)
                    {
                        MessageBox.Show("Input Data Sukses...");
                    }
                    else
                    {
                        MessageBox.Show("Input Data Gagal... ");
                    }

                }
                else
                {
                    MessageBox.Show("Data tidak lengkap");
                }
            }
            catch(Exception ex)
            {
                  MessageBox.Show(ex.ToString());
            }
        }

That Script can run, but after input data and click save buttonm the program stop. 该脚本可以运行,但是在输入数据并单击保存按钮后,程序将停止。

Can anybody help me. 有谁能够帮助我。

Im very Appreciated your answer 我非常感谢您的回答

Thanks 谢谢

form load 形式负荷

 void Form1_Load(object sender, EventArgs e)
        {
            try
            {

                koneksi.Open();
                query = string.Format("SELECT * FROM mahasiswa");
                perintah = new MySqlCommand(query, koneksi);
                adapter = new MySqlDataAdapter(perintah);
                perintah.ExecuteNonQuery();
                ds.Clear();
                adapter.Fill(ds);
                koneksi.Close();
                dgv1.DataSource = ds.Tables[0];
                dgv1.Columns[0].Width = 50;
                dgv1.Columns[0].HeaderText = "ID";
                dgv1.Columns[1].Width = 120;
                dgv1.Columns[1].HeaderText = "Nama Mahasiswa";
                dgv1.Columns[2].Width = 120;
                dgv1.Columns[2].HeaderText = "Jurusan";
                dgv1.Columns[3].Width = 120;
                dgv1.Columns[3].HeaderText = "Email";
                //txtid.clear();
                txtnama.Clear();
                txtjurusan.Clear();
                txtemail.Clear();
                btnedit.Enabled = false;
                btndelete.Enabled = false;
                btnsave.Enabled = true;
                btnsearch.Enabled = true;


            }
            catch (Exception ex) {

                MessageBox.Show(ex.ToString());
            }
        }

Also if your learning CRUD it would be helpful if you made the necessary stored procedures within SQL aswell as attempting it this way. 同样,如果您学习CRUD,那么在SQL中进行必要的存储过程以及以这种方式进行尝试也将很有帮助。

Just create a CREATE, INSERT, UPDATE, DELETE procedure. 只需创建一个CREATE,INSERT,UPDATE,DELETE过程。 Then in your code for an insert example you have this: 然后,在您的插入示例代码中,您将具有以下内容:

public bool Add(string example)
    {
        try
        {

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("[Proc name]", con);
                cmd.CommandType = CommandType.StoredProcedure;
                if (con.State == ConnectionState.Closed)
                    con.Open();
                cmd.Parameters.AddWithValue("@Example", example);

                cmd.ExecuteNonQuery();
                return true;
            }
        }

This allows you to view what happens and to ensure your procedures are working correctly. 这使您可以查看发生了什么并确保您的过程正常运行。 This way allows you to catch exceptions easier, and also validate your inputs easier. 这样,您可以更轻松地捕获异常,还可以更轻松地验证输入。

try this 尝试这个

"INSERT INTO mahasiswa (name,jurusan,mail) values ('{1}','{2}','{3}')", txtnama.Text, txtjurusan.Text, txtemail.Text)";

as your query will instruct mysql to look for 4 values whereas you are passing only 3 values. 因为您的查询将指示mysql查找4个值,而您仅传递3个值。

Do not use string concatenation to build sql command text, use always a parameterized query 不要使用字符串连接来构建sql命令文本,请始终使用参数化查询

query = "INSERT INTO mahasiswa VALUES (@p1,@p2,@p3);";
using(MySqlConnection koneksi = new MySqlConnection(connectionString))
using(MySqlCommand perintah = new MySqlCommand(query, koneksi))
{
     koneksi.Open();
     perintah.Parameters.AddWithValue("@p1", txtnama.Text);
     perintah.Parameters.AddWithValue("@p2", txtjurusan.Text);
     perintah.Parameters.AddWithValue("@p3", txtemail.Text);
     int res = perintah.ExecuteNonQuery();
     if (res == 1)
         MessageBox.Show("Input Data Sukses...");
     else
         MessageBox.Show("Input Data Gagal... ");
}

If you use string concatenation your code will be open to sql injection where a malicious user could wreak havoc with your database ( Look at this funny example ) 如果您使用字符串连接,那么您的代码将可以进行sql注入,恶意用户可能会对数据库进行破坏( 请看这个有趣的示例

Also your format statement is totally wrong, I doubt that your code reaches the point where the database command is executed because you list the arguments for string.Format from the index 1 to index 3 and you supply 3 arguments, but the index should start from zero and end at two. 另外您的format语句是完全错误的,我怀疑您的代码到达执行数据库命令的地步,因为您列出了string的参数。从索引1到索引3的格式并提供3个参数,但是索引应该从零,结束于二。 So you should get an exception on that line. 因此,您应该在那条线上得到一个例外。

Another point to keep note is the using statement . 需要注意的另一点是using语句 As you can see, in my code the using statement will ensure the proper closing and disposing of the connection and command objects. 如您所见,在我的代码中,using语句将确保正确关闭和处理连接和命令对象。 The connection is particularly important to dispose properly because a failure here could break your program later. 正确处理该连接特别重要,因为此处的故障可能会在以后破坏程序。

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

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