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 +"'
Related
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 am getting an error at the ExecuteNonQuery and really don't know why. I spent a lot of time searching the web and realized that User has to be between [], but it hasn't solved my problem.
else {
DataTable table = new DataTable();
string query = "SELECT * FROM [User] WHERE Email = '" + tbMail.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, connectionString);
int count = adapter.Fill(table);
if (count != 0) {
MessageBox.Show("This email is already in use", "Email in use", MessageBoxButtons.OK, MessageBoxIcon.Information);
} else {
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand insertCommand = new OleDbCommand();
adapter = new OleDbDataAdapter();
string encryptedPassword = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(tbPass.Text)));
connection.Open();
string command = "INSERT INTO [User] (Username, Password, Email) VALUES('" + tbUser.Text + "', '" + encryptedPassword + "', " + tbMail.Text + ")";
insertCommand.Connection = connection;
insertCommand.CommandText = command;
adapter.InsertCommand = insertCommand;
adapter.InsertCommand.ExecuteNonQuery();
connection.Close();
}
}
The error is:
There was an error parsing the query. [Token line number,Token line offset,,Token in error,,]"
Your email value must be between quotes, just like username and password.
Another point is that you should use sql parameters to prevent sql injection attacks.
I want to create a login account by matching UserName & Password. I want to save the result in a local variable named as result. When a user logs in, the result should be one, but it always returning -1. My code is following......
protected void LoginBtn_Click(object sender, EventArgs e)
{
string Name = nameTextBox.Text;
string Password = passwordTextBox.Text;
nameTextBox.Text = "";
passwordTextBox.Text = "";
string connectionstring = #"Integrated Security=True;Initial Catalog=HMIS;Data Source=.\SQLEXPRESS";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
string selectquery = "Select ID from UsersInfo where UserName='" + #Name+ "' and Password='" + #Password + "'";
SqlCommand cmd = new SqlCommand(selectquery, connection);
cmd.Parameters.AddWithValue("#UserName", Name);
cmd.Parameters.AddWithValue("#Password", Password);
//object result = cmd.ExecuteNonQuery();
//if (result != null)
int result = (int)cmd.ExecuteNonQuery();
if (result > 0)
Your parameter name was incorrect #UserName whereas in the query string #Name was used.
Try this code.
protected void LoginBtn_Click(object sender, EventArgs e)
{
string Name = nameTextBox.Text;
string Password = passwordTextBox.Text;
nameTextBox.Text = "";
passwordTextBox.Text = "";
string connectionstring = #"Integrated Security=True;Initial Catalog=HMIS;Data Source=.\SQLEXPRESS";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
string selectquery = "Select ID from UsersInfo where UserName='" + #Name+ "' and Password='" + #Password + "'";
SqlCommand cmd = new SqlCommand(selectquery, connection);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#Password", Password);
//object result = cmd.ExecuteNonQuery();
//if (result != null)
int result = (int)cmd.ExecuteNonQuery();
if (result > 0)
The ExecuteNonQuery Method returns the number of row(s) affected by either an INSERT, an UPDATE or a DELETE. For all other types of statements, the return value is -1.
Use the ExecuteReader method instead. This returns a SqlDataReader, which has a HasRows property.
ExecuteNonQuery shouldn't be used for SELECT statements.
I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....
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!