-2

for some reason the following C# code doesn't work:

          int id = 1293842;
        connect.Open();
        string getInfoQuery = "SELECT * FROM table WHERE id = @idpara";
        MySqlCommand getInfo = new MySqlCommand(getInfoQuery, connect);
        getInfo.Parameters.AddWithValue("@idpara", id);
      
     
        string username = "test";
  
     
        MySqlDataReader dataGet = getInfo.ExecuteReader();
        while (dataGet.Read()) {
         
            username = dataGet.GetString("username");
           
        }
        MessageBox.Show(username);

The MessageBox doesn't display the username I look for, but 'test', the value I used for the declaration of my string.

Help is appreciated!

Shadow
  • 33,525
  • 10
  • 51
  • 64
Loli
  • 1
  • 3
  • Have you checked that your table has a username with the id you're using? Have you also checked that the reader is executing successfully? I don't see any exception handling. – greenjaed Feb 02 '21 at 22:29
  • @greenjaed Yes, that is checked before this part of the code. – Loli Feb 02 '21 at 22:42
  • 2
    Put a breakpoint inside the while loop. If code doesn't stop on the breakpoint then you don't have a record with that id (or you are looking at the wrong database) If it stops then the username is 'test' – Steve Feb 02 '21 at 22:46
  • Aside: please see [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice) – Charlieface Feb 02 '21 at 22:52
  • The record that you think is there isn't. Most common cause - you are connected to the wrong database. – mjwills Feb 02 '21 at 22:57
  • I was thinking about this syntax `dataGet["username"]` and `dataGet.GetString(1);` – Cyrille Con Morales Feb 03 '21 at 06:50

2 Answers2

0
MySqlDataReader.GetString Method (Int32)

public override string GetString(
    int i
)

**Parameters i**
Type: System.Int32
The zero-based column ordinal.

Return Value
Type: String
The value of the specified column.

https://dev.mysql.com/doc/dev/connector-net/8.0/html/M_MySql_Data_MySqlClient_MySqlDataReader_GetString.htm

MD. RAKIB HASAN
  • 3,670
  • 4
  • 22
  • 35
0

So, the solution was:

SELECT * FROM table WHERE id=@idpara

instead of

SELECT * FROM table WHERE id = @idpara 
Loli
  • 1
  • 3