C# with MySQL INSERT parameters

后端 未结 9 1952
-上瘾入骨i
-上瘾入骨i 2020-11-28 10:47

Good day to all, I\'m using Visual C# 2010 and MySQL Version 5.1.48-community. I hope you can help me with this code. I don\'t find it working on me. What am I missing?

相关标签:
9条回答
  • 2020-11-28 11:44

    I had the same issue -- Finally tried the ? sigil instead of @, and it worked.

    According to the docs:

    Note. Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL.

    Really? Why don't you just throw an exception if someone tries to use the so called old syntax? A few hours down the drain for a 20 line program...

    MySQL::MySQLCommand

    0 讨论(0)
  • 2020-11-28 11:50

    Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:

    comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;
    

    or:

    comm.Parameters.AddWithValue("@person", Myname);
    

    That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.

    Hope this helps.

    0 讨论(0)
  • 2020-11-28 11:51

    I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

    The following code works lately:

    string connetionString = null;
    connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";
    
    using (MySqlConnection cn = new MySqlConnection(connetionString))
    {
        try
        {
            string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
            cn.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
                cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
                cmd.ExecuteNonQuery();
            }
        }
        catch (MySqlException ex)
        {
            MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
        }
    }
    
    0 讨论(0)
提交回复
热议问题