Reputation: 41
I got a question about c# and mysql. I would like to make a very simpel login form that is connected to my local db. I got the connection to work (tested it) but i have a problem with reading my data that is returned from a select.
I'm trying to put an ID into a string so I can display it(this is just for testing). Now I have searched a lot on google and almost everyone has something like this. When I execute it doesn't give error but my sqldatareader finds nothing. In the first if I ask if it has got any rows and there are none.
What am I doing wrong? My username/password do exist in my db.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace eindwerk
{
public partial class LoginForm : Form
{
string myConnection = "Server=localhost;Database=mydb;Uid=root;Pwd=root;";
MySqlCommand cmd;
MySqlConnection connection;
public LoginForm()
{
InitializeComponent();
connection = new MySqlConnection(myConnection);
connection.Open();
}
private void loginForm_Load(object sender, EventArgs e)
{
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT idlogin FROM login WHERE (username='@username') AND (password='@password') LIMIT 1;";
cmd.Parameters.AddWithValue("@username", txtbxLoginUsername.Text);
cmd.Parameters.AddWithValue("@password", txtbxLoginPassword.Text);
MySqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
if (rdr.HasRows)
{
while (rdr.Read())
{
label1.Text = rdr.GetInt32("idlogin").ToString();
}
}
else
{
lblLoginError.Visible = true;
}
rdr.Close();
}
catch {
lblLoginError.Text = "Nope";
lblLoginError.Visible = true;
}
}
}
}
Upvotes: 0
Views: 1131
Reputation: 41
After a long search i have found the problem ! In my sql query i put username='@username', there lies the problem. You can't use single quotes !!!. I removed the quotes and it works perfectly.
That is whay you get for trusthing a search result on the third page of google...
Thanks to all !
Upvotes: 0
Reputation: 9289
You are calling Read()
Multiple time. Call the While(Reader.Read())
single time and check the result by if(rdr.HasRows()){}
for check result is return or nothing is come in the response.
Upvotes: 1
Reputation: 9425
You are returning only 1 row, but you are calling Read() twice. Your row is effectively discarded before you look at your data.
Upvotes: 0