Home > Software engineering >  MySql Commandstring is switching Values with Columns
MySql Commandstring is switching Values with Columns

Time:08-27

I got a Problem with a little DB Program im working on. The Program is switching Columns with Values und i cant help myself anymore.

This is my String :

string dataString = "INSERT INTO kontakte(ID, Name) VALUES(" client.ID  ","  client.Name ")"

Which i pass to the MySqlCommand with :

MySqlCommand command = new MySqlCommand(dataString, connection);

Funny thing now, this is what i get when i try tu run the Program :

INSERT INTO kontakte(ID, Name) VALUES(12345,SenfMeyer) //WriteLine output of string

Stacktrace ist :    at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
   at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
   at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()

Fehlercode ist : 0 Fehlername ist : Unknown column 'SenfMeyer' in 'field list'

Even funnier, when i replace the Values with the ColumnName, it writes "NULL" in my Database

As you can see the Program thinks that my Values are the Columnnames, does anybode got an idea why this is happening?

CodePudding user response:

There is no switching going on. Just as you wrap literal text in double-quotes in C#, so you use single-quotes in SQL. Anything not wrapped in single-quotes is not considered literal text.

string dataString = $"INSERT INTO kontakte (ID, Name) VALUES ({client.ID}, '{client.Name}')";

This is one reason you don't use string concatenation to build SQL code. If you use parameters then there is no literal text, so you can't get that wrong. That's beyond the scope of this specific question though, so you should research that independently.

  • Related