1

I'm trying to insert into mysql table using this code:

// open connection here
this.conn.Open();

// fields from post request
var email = Request.Form["email"];  
var password = Request.Form["password"];

string sqlInsert = "INSERT INTO mytable(col1, col2) values(?email, ?password)";
MySqlCommand cmd1 = new MySqlCommand(sqlInsert, this.conn);
cmd1.Parameters.Add("?email", email);
cmd1.Parameters.Add("?password", password);
cmd1.ExecuteNonQuery();

here: cmd1.Parameters.Add("?email", email); I am getting error:

cannot convert from 'string' to 'MySql.Data.MySqlClient.mysqlDBType'

What I'm doing wrong?

0

2 Answers 2

5

You are using the Add method the wrong way.

It should be cmd1.Parameters.Add("?email", MySqlDbType.VarString).Value = email;
(You can choose another overload if you want to, but this is the easiest to use most of the times.)

Note: I'm guessing the data type of email is VarString.

Sign up to request clarification or add additional context in comments.

4 Comments

Or he can use AddWitheValue variant
@styx AddWithValue means that the MySql driver must infer the actual data type of the parameter supplied - which could be dangerous as it may lead to exceptions or even worst - wrong data. For more information, read this.
@ZoharPeled here the client is SqlClient, which I have seen works fine while it tries to figure out the underlying type especially common data type like string, infact micro orm like Dapper also does it without an issue
@MrinalKamboj AddWithValue works find on many ADO.Net client implementations... until it doesn't. I wouldn't count on it "working fine" when I know for a fact that sometimes it doesn't, and there's a perfectly easy and safer way to send parameters to the database. The couple of extra key strokes are totally worth it.
1

Hi you need to convert your string parameter to MySQL Db type parameter, I usually create a function in code like this:

protected DbParameter GetParameter(string parameterName, object parameterValue)
        {
            DbParameter parameterObject = new MySqlParameter(parameterName, 
            parameterValue ?? DBNull.Value);

            //this defines if it is an input or output parameter
            // you can also have output paramters
            parameterObject.Direction = ParameterDirection.Input;

            return parameterObject;
        }

and call it int our code like this:

       var somevariable = "somevalue";

        var parameters = new List<DbParameter>
        {
            base.GetParameter("parametermnamehere", somevariable),
        };

Simple and Clean, hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.