String sqlCheckPass =
"Select * from Login where Username like #Username and Password like #Password";
SqlCommand SqlCom = new SqlCommand(sqlCheckPass, myConnection);
SqlCom.Parameters.Add(new SqlParameter("#Username", sUserName));
SqlCom.Parameters.Add(new SqlParameter("#Password", sPassword));
myConnection.Open();
SqlDataReader myreader;
myreader = SqlCom.ExecuteReader();
int id = -1;
ErrorBox.InnerHtml = "Username:" + sUserName + ":" + sPassword + ":<br/>";
while (myreader.HasRows)
{
id = (int)myreader["id"];
String sUser = (String)myreader["Username"];
String sPass = (String)myreader["Password"];
ErrorBox.InnerHtml += "UserId is <b>" + id + "</b> " + sUser + ":" + sPass + ":<br >";
Session["LoginID"] = id;
Server.Transfer(ReturnPage);
}
if (id == -1)
{
ErrorBox.InnerHtml = "Incorrect Password";
}
myConnection.Close();
catch (Exception err)
{
ErrorBox.InnerHtml = "Error Getting Option ID" + err.Message;
}
I added a breakpoint at myreader = SqlCom.ExecuteReader(); and it keeps returning myreader as null and HasRows = False, but it does have rows. So, it keeps validating my login as incorrect since id = -1,
Help?
You didn't connect your reader to your SQL connection/command?
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
The problem might be the LIKE in your query with the SqlParameters. Try
String sqlCheckPass =
"Select * from Login where Username like '%' + #Username + '%' and Password like '%' + #Password + '%'";
Bryan Denny's answer above is correct, however, I'll enclose all of the code inside using statements as shown below:
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand SqlCom = dataConnection.CreateCommand())
{
SqlCom.CommandText = "Select * from Login where Username like #Username and Password like #Password";
SqlCom.Parameters.Add(new SqlParameter("#Username", sUserName));
SqlCom.Parameters.Add(new SqlParameter("#Password", sPassword));
dataConnection.Open();
SqlDataReader myreader;
myreader = SqlCom.ExecuteReader();
dataConnection.Close();
}
}
I didn't add all of your code to this snippet, I figured you get the idea.
Also, you could try modifying the select statement to return a count of records since this is all you need anyways, a number:
SELECT COUNT(*) FROM Login WHERE Username like #Username AND Password like #Password
Good luck!
Related
In SQL Server Management studio, when you do a SELECT query, you also get a message aswell as the results. That message i would like to use in a Rich Textbox. Is that possible?
The Message i'm talking about is this:
I have this code so far, that also fills comboboxes with results, but i would like my rich textbox to show the message aswell:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
Con.Close();
}
The GUI looks like this:
Use SqlConnection.InfoMessage event,
This event occurs when SQL Servers returns a warning or informational message.
You don't need to look at the message. You can just look at the reader's RowsEffected, like this :
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
var recordsEffected = reader.RecordsAffected;
}
ExecuteNonQuery() - returns the number of rows affected.
SqlCommand comm;
// random code
int numberOfRecords = comm.ExecuteNonQuery();
EDIT:
For select queries you can use ExecuteScalar() -
String sqlQuery = "SELECT count(USERNAME) FROM PERSONAL";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
try
{
conn.Open();
//Since return type is System.Object, a typecast is must
count = (Int32)cmd.ExecuteScalar();
}
I got it all to work. Thanks for the big help. Much apprieciated!
I will show it all if any can use any off it :D
Ended up with this:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
}
var countUsers = fromComboBox.Items.Count;
movePostMessage.Text = countUsers + " brugere er fundet";
}
}
And on the button click i've made this:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
string SQL1 = "UPDATE DEBSALDO SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL2 = "UPDATE SERVHEAD SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL3 = "UPDATE SERVICEB SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL4 = "UPDATE PERSONAL SET ACOUNTCYID = NULL WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
SqlCommand cmd1 = new SqlCommand(SQL1, Con);
SqlCommand cmd2 = new SqlCommand(SQL2, Con);
SqlCommand cmd3 = new SqlCommand(SQL3, Con);
SqlCommand cmd4 = new SqlCommand(SQL4, Con);
Int32 rowsAffectedOnUpdate1 = cmd1.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate2 = cmd2.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate3 = cmd3.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate4 = cmd4.ExecuteNonQuery();
movePostMessage.Text = rowsAffectedOnUpdate1 + " regninger flyttet fra tidligere brugers debitor saldo \r\n" + rowsAffectedOnUpdate2 + " regninger flyttet med tidligere bruger som ejer \r\n" + rowsAffectedOnUpdate3 + " ydelser flyttet med tidligere bruger som ejer \r\n" + rowsAffectedOnUpdate4 + " kontoplan nulstillet";
}
And the GUI to it:
Initially I set both columns, username and pass, in my database(SQL Server 2012) as int in the employeeinfo table. When I entered the correct credentials, I was able to log in successfully.
However, when I changed both both columns, username and pass, to varchar(50) and entered the correct credentials, I get a message indicating username and password were incorrect.
Any idea why? Code posted below.
private void loginbutton_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(ConString);
try
{
con.Open();
string query = "select * from employeeinfo where username='" +
this.txt_username.Text + "' and pass=' " +
this.txt_password.Password +"' ";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count++;
}
if (count == 1)
{
MessageBox.Show("Open Sesame!");
second sec = new second();
sec.ShowDialog();
}
if (count > 1)
{
MessageBox.Show("Note to developer: Enforce unique constraints!");
}
if (count < 1)
{
MessageBox.Show("Username and password is not correct. Please try again!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Try use parameters :
cmd.CommandText = "select * from employeeinfo where username=#username and pass=#pass ";
cmd.Parameters.Add("#username", SqlDbType.VarChar);
cmd.Parameters["#username"].Value = this.txt_username.Text;
cmd.Parameters.Add("#pass", SqlDbType.VarChar);
cmd.Parameters["#pass"].Value = this.txt_password.Password;
SqlDataReader sdr = cmd.ExecuteReader();
In this line you have an extra space after pass=':
string query = "select * from employeeinfo where username='"
+ this.txt_username.Text + "' and pass=' " + this.txt_password.Password +"' ";
Here is the fixed line.
string query = "select * from employeeinfo where username='"
+ this.txt_username.Text + "' and pass='" + this.txt_password.Password + "' ";
It wouldn't hurt to store your passwords more securely (hashed, not plaintext) and learn a bit about SQL injection, though. :)
I get this error when trying to insert data into my database.
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'User'.
Here is the code:
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(
Properties.Settings.Default.BlackBookDBConnectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO User (Username, Password, SecurityQuestionOne, "
+ "SecurityQuestionTwo, SecurityAnswerOne, SecurityAnswerTwo); VALUES ("
+ txtRegisterUsername.Text + ","
+ txtRegisterPassword.Text + ","
+ lstRegisterSecurityQuestionOne.SelectedText + ","
+ lstRegisterSecurityQuestionTwo.SelectedItem + ","
+ txtRegisterSecurityAnswerOne.Text + ","
+ txtRegisterSecurityAnswerTwo.Text + ")";
cmd.CommandText = "INSERT INTO USer ()";
cmd.Connection = connection1;
connection1.Open();
cmd.ExecuteNonQuery();
connection1.Close();
}
I have edited my code. However it still does not insert anything into my database for some reason.
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (#Username,#Password,#QuestionOne,#AnswerOne,#QuestionTwo,#AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("AnswerTwo", answerTwo);
command.Connection = connection1;
connection1.Open();
command.ExecuteNonQuery();
connection1.Close();
}
Remove this line:
cmd.CommandText = "INSERT INTO USer ()";
EDIT
After looking at your new code, you have wrong parameters names (missing #). You should change your code to this:
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("#Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("#Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("#QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("#QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("#AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("#AnswerTwo", answerTwo);
Remove second line assigning cmd.CommandText - it's overwriting the first one
User is a keyword in SQL server, if you have a table with that name (which you should not) enclose it into square brackets:
cmd.CommandText = "INSERT INTO [User] ...
On a side note - learn about parametrized queries. They're a great way to avois SQL injection attacks (not to mention confusing mess of string concatenation)
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
connection1.Open();
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (#Username,#Password,#QuestionOne,#AnswerOne,#QuestionTwo,#AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.Add("#Username", SqlDbType.VarChar, 200).Value = userName;
string password = txtRegisterRepeatPassword.Text;
command.Parameters.Add("#Password", SqlDbType.VarChar, 200).Value = password;
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.Add("#QuestionOne", SqlDbType.VarChar, 200).Value = questionOne;
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.Add("#QuestionTwo", SqlDbType.VarChar, 200).Value = questionTwo;
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.Add("#AnswerOne", SqlDbType.VarChar, 200).Value = answerOne;
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.Add("#AnswerTwo", SqlDbType.VarChar, 200).Value = answerTwo;
command.ExecuteNonQuery();
connection1.Close();
}
I just don't know how to check if the users exists in the database and stop it from inserting a new row to the db (which will cause an error as I set the user to be a primary key)
protected void Button1_Click1(object sender, EventArgs e)
{
{
OleDbConnection myconnection = new OleDbConnection();
myconnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Event.mdb";
myconnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
myCommand.CommandType = CommandType.Text;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
myCommand.CommandText = query;
try
{
int amountOfUsers = (int)myCommand.ExecuteScalar();
if (amountOfUsers < 1)
{
String myQuery = "insert into users (uname,upassword,email,type) Values ('" + UserName.Text + "','" + Password.Text + "' ,'" + Email.Text + "',' user');";
myCommand.CommandText = myQuery;
myCommand.ExecuteNonQuery();
Label1.Text = "user registered";
}
else
{
Label1.Text = "user already exists";
UserName.Text = "";
Email.Text = "";
}
}
finally
{
myconnection.Close();
}
}
}
correct your query:
query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'" ,UserName.Text );
Your question isn't clear at all but I can suggest a few things..
First of all, I think you forget to use your uname as a second parameter in your:
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
line. You used {0} but never point any value to this parameter. (I assume you don't have a username called {0}) Like;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'", UserName.Text);
As a second, please always use parameterized queries. This kind of string concatenations are open for SQL Injection attakcs.
Like;
String myQuery = "insert into users (uname,upassword,email,type) Values (#uname, #upassword, #email, #type)";
OleDbCommand myCommand = new OleDbCommand(myQuery);
myCommand.Parameters.AddWithValue("#uname", UserName.Text);
myCommand.Parameters.AddWithValue("#upassword", Password.Text);
myCommand.Parameters.AddWithValue("#uname", Email.Text);
myCommand.Parameters.AddWithValue("#uname", "user");
i want to check if the username in UserName.Text is availble in the
data base or no and if it does i want to stop from inserting new data
Than you should use SELECT first to check your username is exist in your database or not like;
string query = string.Format("SELECT * FROM users WHERE uname = '{0}'", UserName.Text);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
SqlDataReader reader = myCommand.ExecuteReader();
if(reader.HasRows)
{
//Your username exist in your database
}
else
{
//Doesn't exist
}
you have missing the parameter uname , you have pass the text of UserName textbox to uname
for eg
"SELECT COUNT(*) FROM users WHERE uname='" + UserName.Text +"'
I want to read an int value from my table. but I faced with error
this is my code. please help me to edit my code.
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
SqlDataReader rdr = cmd.ExecuteReader();
// loop over all rows returned by SqlDataReader
while(rdr.Read())
{
RemainedChargeLbl.Text=rdr.GetString(0);
}
To read one value you don't need reader. Use SqlCommand.ExecuteScalar Method which executes query and returns first column of the first row in result set returned by query:
int value = (int)cmd.ExecuteScalcar();
BTW it's better to create command object with sqlc.CreateCommand() - it creates appropriate command and automatically assigns connection to it.
You are not assigning connection object sqlc to the SqlCommand.
Add this:
cmd.Connection=sqlc;
Complete Solution:
sqlc = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection=sqlc;
string username = HttpContext.Current.User.Identity.Name.ToString();
cmd.CommandText = #"SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
//string RemainedCharge;
sqlc.Open();
RemainedChargeLbl.Text =((int) cmd.ExecuteScalar()).ToString();
Use this code:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT RemainedCharge "
+ " FROM aspnet_Users "
+ " WHERE UserName = #UserName ";
cmd.Parameters.Add(new SqlParameter("#UserName", username);
cmd.Parameters.AddWithValue("#id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}