Creating Login Form Using Visual Studio
I'm new to Visual Studio 2010 and I'm trying to create a Login form.
I have this code.
OdbcConnection con = new OdbcConnection("host=localhost;usr=root;password=admin;db=timekeeping;");
OdbcCommand cmd = new OdbcCommand("SELECT * FROM receptionist WHERE username = '" + username_login.ToString() + "' AND password = '" + password_login.To开发者_StackOverflowString() + "';");
cmd.Connection = con;
con.Open();
OdbcDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (reader.GetString(0) != 1)
{ return false; }
else
{ return true; }
}
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
There are errors but I don't know what is the problem with that. Here's a screenshot:
Hoping that someone ca help me..
Thanks
Your code is vulnerable to SQL Injection. Never use string concatenations when building your SQL queries. Use parametrized queries instead:
public bool IsValid(string username, string password)
{
using (var conn = new OdbcConnection("host=localhost;usr=root;password=admin;db=timekeeping;"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT count(*) FROM receptionist WHERE username = @username AND password = @password;";
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
var count = (long)cmd.ExecuteScalar();
return count > 0;
}
}
and then call like this:
bool isValid = IsValid(username_login.ToString(), password_login.ToString());
Also if you are using SQL Server you are better with SqlConenction instead of ODBC driver.
You can't compare a string to an int which you are trying here:
if (reader.GetString(0) != 1)
You could use GetInt32:
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcdatareader.getint32.aspx
And you shouldn't build your SQL like this but use parameters instead of just constructing a string. You're vulnerable to SQL injection with this way of constructing your SQL code.
Well the error message is pretty OdbcDataReader.GetString returns a string not an int. Therefore you can't compare it. See MSDN
You probably want to check the length of it? if (reader.GetString(0).Length != 1)
Replace in your code this line
if (reader.GetString(0) != 1)
with this
if (int.Parse(reader.GetString(0)) != 1)
Second,
In your userLogin() method you are tryin to return a value whereas the reeturn type is void. Change the return type.
if (reader.GetString(0) != "1")
{ return false; }
else
{ return true; }
Trying to compare an int
and a string
won't really work.
you can also do
if (Convert.ToInt32(reader.GetString(0)) != 1)
{ return false; }
else
{ return true; }
However, in some cases this might not work.
And in addition, I'd rather use GetSqlString
and convert it instead of using GetString
because I had too many problems with null
s when I was coding.
精彩评论