AM031447
AM031447

Reputation: 495

How do I Use C # Query MYSQL data And displays?

I try to follow the teaching, but still fails

I tried to use this code to query NAME but did not succeed in show

My database: testdb table: playdata

I want to use the primary key 'SID' to get NAME

I think SL1 should display TEST NAME, but nothing show

Or am I doing wrong?

I found the insert information in other teaching, his success

But the query fails

string connStr = "server=127.0.0.1;port=3306;uid=root;pwd=123123;database=testdb;";
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand command = conn.CreateCommand();
try
{
    conn.Open();
    String cmdText = "SELECT NAME * FROM playdata WHERE SID = 001";
    command = new MySqlCommand(cmdText, conn);
    String _name = (string)command.ExecuteScalar();
    SL1.Text = _name;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
    switch (ex.Number)
    {
        case 0:
            SL1.Text = "Can not connect";
            break;
        case 1045:
            SL1.Text = "Input error";
            break;
    }
}
Console.ReadLine();
conn.Close();

----*edit ----Efficient coding

    string connStr = "server=127.0.0.1;port=3306;uid=root;pwd=123123;database=testdb;";
    MySqlConnection conn = new MySqlConnection(connStr);
    MySqlCommand command = conn.CreateCommand();

    String cmdText = "SELECT NAME FROM playdata WHERE SID = 'S01'";
    command = new MySqlCommand(cmdText, conn);
    conn.Open();
    try {
        string str = command.ExecuteScalar().ToString();
        SL1.Text = str;
    } catch {
        SL1.Text = "error";
    }

Upvotes: 1

Views: 51

Answers (1)

VMAtm
VMAtm

Reputation: 28345

The error is in your query, you've forgot to remove * sign. Your code should be like this:

String cmdText = "SELECT NAME FROM playdata WHERE SID = 001";

And, may be, you should add '' for your SID filter, as it can be not a integer:

String cmdText = "SELECT NAME FROM playdata WHERE SID = '001'";

Upvotes: 4

Related Questions