Hi,
why i can put only one value in MySql db?
When put first value, show this error:
"Parameter "?city" has already been defined"
Ant stop on this line:
cmd.Parameters.Add(new MySqlParameter("?city", MySqlDbType.VarChar, 40)).Value = city;

conn = new MySql.Data.MySqlClient.MySqlConnection();
            cmd = new MySql.Data.MySqlClient.MySqlCommand();

            string strConnection = "SERVER=localhost;" +
                "DATABASE=new;" +
                "UID=root;" +
                "PASSWORD=;";

            conn.ConnectionString = strConnection;


            try
            {
                conn.Open();
                cmd.Connection = conn;

                cmd.CommandText = "INSERT INTO test (city) VALUES(?city)";
                cmd.Prepare();

                foreach(string city in cityList)
                {
                    cmd.Parameters.Add(new MySqlParameter("?city", MySqlDbType.VarChar, 40)).Value = city;
                    
                    cmd.ExecuteNonQuery();
                }
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            }

Edited 6 Years Ago by gloris: n/a

Hi,
why i can put only one value in MySql db?
When put first value, show this error:
"Parameter "?city" has already been defined"
Ant stop on this line:
cmd.Parameters.Add(new MySqlParameter("?city", MySqlDbType.VarChar, 40)).Value = city;

conn = new MySql.Data.MySqlClient.MySqlConnection();
            cmd = new MySql.Data.MySqlClient.MySqlCommand();

            string strConnection = "SERVER=localhost;" +
                "DATABASE=new;" +
                "UID=root;" +
                "PASSWORD=;";

            conn.ConnectionString = strConnection;


            try
            {
                conn.Open();
                cmd.Connection = conn;

                cmd.CommandText = "INSERT INTO test (city) VALUES(?city)";
                cmd.Prepare();

                foreach(string city in cityList)
                {
                    cmd.Parameters.Add(new MySqlParameter("?city", MySqlDbType.VarChar, 40)).Value = city;
                    
                    cmd.ExecuteNonQuery();
                }
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine("Error " + ex.Number + " has occurred: " + ex.Message);
            }

The problem is that you are adding your parameter inside the

foreach

foreach loop. If the are more than one cities in the cityList, then your code is going to try to add ?city parameter more than once, which is wrong. Instead do the following:

cmd.Parameters.Add(new MySqlParameter("?city", MySqlDbType.VarChar, 40));

foreach(string city in cityList)
{
      cmd.Parameters[?city].Value = city;
      cmd.ExecuteNonQuery();
}
This article has been dead for over six months. Start a new discussion instead.