将C#数据传递给MySQL

时间:2016-03-19 19:23:17

标签: c# mysql

我正在尝试将数据从C#中的某些文本框传递到MySQL数据库,但每次我从C#应用程序中单击提交时,该行都会创建空格,就好像我的文本框是空的一样。

public void Insert()
{
    string query = "insert into albertolpz94.miembros(usuario,contraseña,permisos,nombre,apellidos) values('" + userAdmin.registroUsuario.Text + "','" + userAdmin.registroContraseña.Text + "','" + userAdmin.registropermisos2 + "','" + userAdmin.registroNombre.Text + "','" + userAdmin.registroApellidos.Text + "');";
    //open connection
    if (this.OpenConnection() == true)
    {
        //create command and assign the query and connection from the constructor
        MySqlCommand cmd = new MySqlCommand(query, connection);

        //Execute command
         cmd.ExecuteNonQuery();

        //close connection
        this.CloseConnection();
    }
} 
例如,registroUsuario是我的userAdmin类中的公共文本框,数据库名为" albertolpz94"这张桌子是" miembros"。我想知道为什么会发生这种情况或如何使用参数(如有人建议的那样),因为我是Mysql的新手> C#

2 个答案:

答案 0 :(得分:2)

首先,要知道连接和命令变量需要妥善处理。我们通过使用using块来确保这一点:

using (MySqlConnection conn = new MySqlConnection())
    using (MySqlCommand cmd = new MySqlCommand()) {

    // ensure your connection is set
    conn.ConnectionString = "your connection string";
    cmd.Connection = conn;

}

然后,使用CommandText处理@ParamName以表示参数:

using (MySqlConnection conn = new MySqlConnection())
    using (MySqlCommand cmd = new MySqlCommand()) {

    // ensure your connection is set
    conn.ConnectionString = "your connection string";
    cmd.Connection = conn;

    cmd.CommandText = "INSERT INTO ThisTable (Field1, Field2) VALUES (@Param1, @Param2);";

}

接下来,使用cmd.Parameters.AddWithValue()插入您的值。这应该是这样的,所以框架可以避免SQL注入攻击(Rustam的回答是非常危险的,就像你做的那样):

using (MySqlConnection conn = new MySqlConnection())
    using (MySqlCommand cmd = new MySqlCommand()) {

    // ensure your connection is set
    conn.ConnectionString = "your connection string";
    cmd.Connection = conn;

    cmd.CommandText = "INSERT INTO ThisTable (Field1, Field2) VALUES (@Param1, @Param2);";

    cmd.Parameters.AddWithValue("@Param1", userAdmin.YourProperty);
    cmd.Parameters.AddWithValue("@Param2", userAdmin.YourOtherProperty);

}

最后,您可以打开连接并执行它:

using (MySqlConnection conn = new MySqlConnection())
    using (MySqlCommand cmd = new MySqlCommand()) {

    // ensure your connection is set
    conn.ConnectionString = "your connection string";
    cmd.Connection = conn;

    cmd.CommandText = "INSERT INTO ThisTable (Field1, Field2) VALUES (@Param1, @Param2);";

    cmd.Parameters.AddWithValue("@Param1", userAdmin.YourProperty);
    cmd.Parameters.AddWithValue("@Param2", userAdmin.YourOtherProperty);


    cmd.Connection.Open();
    cmd.ExecuteNonQuery();
    cmd.Connection.Close();
}

最后,要意识到当这些命令和连接变量退出using块时,它们将被妥善处理掉。 using块确保正确处置,无论可能抛出任何异常,或者我们是否忘记关闭/处置自己。

现在,为了进行有用的调试,将核心执行和连接打开包装在try/catch块中,如果有的话,将异常写入输出窗口:

using (MySqlConnection conn = new MySqlConnection())
    using (MySqlCommand cmd = new MySqlCommand()) {

    // ensure your connection is set
    conn.ConnectionString = "your connection string";
    cmd.Connection = conn;

    cmd.CommandText = "INSERT INTO ThisTable (Field1, Field2) VALUES (@Param1, @Param2);";

    cmd.Parameters.AddWithValue("@Param1", userAdmin.YourProperty);
    cmd.Parameters.AddWithValue("@Param2", userAdmin.YourOtherProperty);

    try {
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
    } catch (Exception e) {
        System.Diagnostics.Debug.WriteLine("EXCEPTION: " + e.ToString());
    }
}

此时你在异常捕获上设置断点并检查你的本地窗口以查看你的状态...在本地人中,你应该看到你的cmd变量...展开它,寻找Parameters集合,展开,检查计数和值等,如下所示:

enter image description here

答案 1 :(得分:0)

最好的选择是调试并查看输入是否到达查询部分。同样,确保在执行查询之前打开连接。提及你正在做的输入变量并不是最好的做法。相反,试试这个:

public void Insert()
    {
        string query = "insert into albertolpz94.miembros(usuario,contraseña,permisos,nombre,apellidos) values('{0}','{1}','{2}','{3}','{4}')", userAdmin.registroUsuario, userAdmin.registroContraseña, userAdmin.registropermisos2, userAdmin.registroNombre, userAdmin.registroApellidos;
        //DOUBLECHECK IF YOU REALLY OPENED A CONNECTION

        if (this.OpenConnection() == true)
        {
            //create command and assign the query and connection from the constructor
            MySqlCommand cmd = new MySqlCommand(query, connection);

            //Execute command
             cmd.ExecuteNonQuery();

            //close connection
            this.CloseConnection();
        }
    }  

另外,请检查connection

的有效性