且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#代码将数据插入到mysql数据库中

更新时间:2023-01-29 09:09:02

查看文章 [在MySQL中插入,更新,删除,显示数据使用C#]

这个例子有点简单,这样你很容易受到' SQL注入'的影响,***使用参数化查询,请参见此处的示例:帮助我了解C#中的MySqlCommand参数 [ ^ ]



另一个想法是使用像 NHibernate 这样的ORM >为您处理查询,但这是一个非常陡峭的学习曲线。其中一个优点是您可以轻松地将数据库切换到另一个数据库,例如的PostgreSQL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;

public partial class CDA_Form : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void formsubmit(object sender, EventArgs e)
    {


       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        String MyConString = "SERVER=localhost;DATABASE=inturealty;UID=techprodigy;PASSWORD=tech@123;";
        using (MySqlConnection connection = new MySqlConnection(MyConString))
        {
            try
            {
                

                string cmdText = "INSERT INTO cda_form(Property_Address,sellerName,buyerName,closingDate,commission,transactionFee,refferal1,refferal2) VALUES (@add,@S,@B,@c1,@caln,@br,@sr)";
                MySqlCommand cmd = new MySqlCommand(cmdText, connection);
                cmd.Parameters.AddWithValue("@add", '"+add.Text,add1.Text,c.Text,st.Text,zip.Text+'");
                cmd.Parameters.AddWithValue("@S", "'+S.Text+'");
                cmd.Parameters.AddWithValue("@B", "'+B.Text+'");
                cmd.Parameters.AddWithValue("@c1", "'+c1.Text,c2.Text,c3.Text+'");
                cmd.Parameters.AddWithValue("@caln", "'+caln.Text+'");
                cmd.Parameters.AddWithValue("@br", "'+br.Text+'");
                cmd.Parameters.AddWithValue("@sr", "'+sr.Text+'");

                string add = add.Text + " " + add1.Text + " " + c.Text + " " + zip.Text;
                MySqlCommand comm.Parameters.AddWithValue("@add", add);

                connection.Open();
                int result = cmd.ExecuteNonQuery();
                //lblError.Text = "Data Saved";
            }
            catch (Exception)
            {
                MessageBox.Show("not entered");
                //lblError.Text = ex.Message;
            }
        }
    }

}



What I have tried:

string add = add.Text + " " + add1.Text + " " + c.Text + " " + zip.Text;
                MySqlCommand comm.Parameters.AddWithValue("@add", add);

See this article [Insert, Update, Delete, Display Data in MySQL Using C#]
This example is a bit simplistic, this way you are vulnerable to 'SQL injection', it's better to use parameterized queries, see example here: Help me for MySqlCommand parameters in C#[^]

Another idea would be to use an ORM like NHibernate which does the query handling for you, but this is quite a steep learning curve. One of the advantages is that you can easily switch the database to another one e.g. PostgreSQL.