I am creating a user login for my software which is connected to Access, I keep on getting the same error which highlights the line ' i = (int)command.ExecuteScalar();' saying...
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error (missing operator) in query expression 'Username= 'MGRjs' AND Password 'Candy''.
private void LoginButton_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\Loughborough\3rd Year\Individual Project\StockManagement system\Database.accdb");
OleDbCommand command = new OleDbCommand();
int i = 0;
if (IDtbx.Text == string.Empty)
{
MessageBox.Show("Please log in");
}
command = new OleDbCommand("select count(*)from NewUser where Username= '" + IDtbx.Text + "' AND Password '" + PSWtbx.Text + "'", connection);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
i = (int)command.ExecuteScalar();
}
connection.Close();
if (i > 0)
{
MainSystem mainForm = new MainSystem();
mainForm.FormClosed += new FormClosedEventHandler(Login_FormClosed);
mainForm.Show();
this.Hide();
LoginError.Visible = false;
}
else
{
LoginError.Visible = true;
}
}
Your SQL is wrong so your database is raising and error.
select count(*)from NewUser where Username= 'blablalbla' AND Password 'whatever'
You are missing the = between the password and the value.
BTW, your code is prone to SQL Injection, please consider using parametrized queries yo avoid security flaws,
Related
I'm trying to make a program that searches data from MySQL database and displays the values in the text box using Text Change event.
So far here is my code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sqlstring = "database = db_phonebook; user = root; password = ''; server = 'localhost'; SSL Mode = None";
MySqlConnection mysqlcon = new MySqlConnection(sqlstring);
MySqlCommand mysqlcom;
MySqlDataReader mdr;
mysqlcon.Open();
string selectquery = "SELECT * FROM 'tbl_phonebook' WHERE CID =" + cid.Text;
mysqlcom = new MySqlCommand(selectquery, mysqlcon);
mdr = mysqlcom.ExecuteReader();
if (mdr.Read())
{
name.Text = mdr.GetString("Name");
address.Text = mdr.GetString("Address");
contact.Text = mdr.GetString("Contact_Number");
email.Text = mdr.GetString("Email_Address");
}
else
{
MessageBox.Show("Record Not Found!");
}
mysqlcon.Close();
}
But the error says MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''tbl_phonebook' WHERE CID =' at line 1'
any idea how do I fix this?
I'm sorry to say there is a LOT that is wrong here, some of it much more important even than the bug you know about. Try this instead, and learn from the patterns shown:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string constring = "database = db_phonebook; user = root; password = ''; server = 'localhost'; SSL Mode = None";
//backticks instead of single quotes around the table/object name
string sql = "SELECT * FROM `tbl_phonebook` WHERE CID = #CID";
//using blocks make sure the connection is closed and disposed,
// EVEN IF AN EXCEPTION IS THROWN
// Original code would have left the connection hanging open.
using (var con = new MySqlConnection(constring))
using(var cmd = new MySqlCommand(sql, con))
{
//parameterized query instead of string concatenation.
// THIS IS A **HUGE** DEAL!!
// It's important enough you should STOP and go FIX
// any code you have anywhere that already uses concatenation.
cmd.Parameters.AddWithValue("#CID", cid.Text);
con.Open();
using (var mdr = cmd.ExecuteReader())
{
if (mdr.Read())
{
name.Text = mdr.GetString("Name");
address.Text = mdr.GetString("Address");
contact.Text = mdr.GetString("Contact_Number");
email.Text = mdr.GetString("Email_Address");
}
else
{
//Do NOT show an interrupting textbox that steals focus from
// an actively typing user based on a textchanged event!
name.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
}
}
}
}
Not sure why I get an error every single time i try to connect. I tried so many things. When i type the wrong password while connecting manually it says access not granted or whatever so I know it connects but when it connects I get this weird error.
An unhandled exception of type
'System.Collections.Generic.KeyNotFoundException' occurred in
mscorlib.dll Additional information: The given key was not present in
the dictionary.
For localhost it works when I have this connection string.
server=localhost; port=3306; USER ID=root; password=***; database=database;
but when I change the server user id and password it decides to not work.
The exception is thrown at cn.Open();
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection cn = new MySqlConnection();
cn.ConnectionString = "server=db4free.net ;port=3306;
user=goof; password=pwd; database=s;";
cn.Open();
MySqlCommand cmd = new MySqlCommand("select * from users where
username = '"
+ textBox1.Text + "',
and password = '"
+ textBox2.Text + "'", cn);
MySqlDataReader dr;
dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if(count == 1)
{
MessageBox.Show("success");
}
else
{
MessageBox.Show("error");
}
}
The problem is the user=goof field should be user id=goof.
Change your connection string into this:
cn.ConnectionString = "server=db4free.net ;port=3306; USER ID=goof; password=pwd; database=s;";
try using "user id" or "uid" instead of just "user" and let us know if its does the job!
I am new to C#. I have Activation Data Type Bit in my database default value 0.
My question is how can I block user to login before activation email send
after registration is completed the activation is null in database but still user can login how can I fix this problem please help.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Loginbtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where UserName='" + UserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select password from UserData where UserName='" + UserName.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString().Replace(" ", "");
if (password == Password.Text && UserName.Text == "Admin" )
{
Session["New"] = UserName.Text;
Response.Redirect("~/Admin/UserManager.aspx");
}
if (password == Password.Text)
{
Session["New"] = UserName.Text;
Response.Redirect("~/Account/UserPage.aspx");
}
else
{
invalidlbl.Text = "Please check your username and password";
}
}
}
Here is the image of my database:
You said activation is null in database. So, when user tried to login, fetch and check if the activation is still null in database and if so then just so a message to user saying activate your account first and redirect him/her to home page.
EDIT: per your comment, not going to give you full code but here is an example of what I am saying. BTW, consider using SQL Parameter to avoid SQL Injection attack.
string checkuser = "select count(*) from UserData where UserName=#uname and activation != null";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#uname", SqlDbType.VarChar).Value = UserName.Text.Trim();
int temp = Convert.ToInt32(com.ExecuteScalar());
if(temp > 0)
{
// do processing
}
else
{
// not activated ... throw alert
}
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Could not use ''; file already in use
This is where the error points at:
da.Fill(dt);
The database is located at C:\ChattBankMDB.mdb on my computer.
Database: http://puu.sh/hjQj0/d86ede4c00.png
When I press the button1, I would like for the form to follow up and login on the Customer database else a messagebox.show will say failure to login.
Button on form:
public partial class CustLogin : Form
{
OleDbConnection db = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\ChattBankMDB.mdb");
OleDbDataAdapter da = new OleDbDataAdapter();
DataTable dt = new DataTable();
public CustLogin()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
da = new OleDbDataAdapter("Select CustID, CustPassword From Customers", db);
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (UserText.Text == dt.Rows[i]["CustID"] && PassText.Text == dt.Rows[i]["CustPassword"])
{
WelcomeCust f = new WelcomeCust();
this.Hide();
f.Show();
}
else
{
MessageBox.Show("FAILURE TRY AGAIN");
}
}
}
I've noticed a couple of potential issues:
Database Injection.
Password in plain text.
Utilizing SqlConnection.
A .mdb isn't a SQL database, it is actually a Microsoft Access database. So you'll want to actually use ADO.NET connection. So your code should actually be:
private readonly string dbConnection = ConfigurationManager.ConnectionStrings["..."].ConnectionString;
private const string query = "SELECT * FROM [Example] WHERE ([Id] = #Id);";
public void Example()
{
using(var connection = new OleDbConnection(dbConnection))
using(var command = new OleDbCommand(query, connection))
{
// Apply parameter, open connection, etc.
}
}
You utilize parameters to avoid a sub-query being introduced. As for your password in plain text you should take a look at BCrypt or another library for a Salt / Hash approach.
Then the change to the connection should alleviate your issue.
Your next issue I believe stems from the Fill being before you build your data table.
The database is an Acces database , so you need to use OleDB to connect to it.
Moreover, the query can cause errors.
Replace :
("Select* from Customers where CustID ='" + UserText.Text +"'
and CustPassword =" + PassText.Text + '"', conn)
By :
("Select * from Customers where CustID = '" + UserText.Text + "'
and CustPassword = '" + PassText.Text + "'", conn);
i had the exact name in my database yet i still keep getting that error as titled.
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Image Link : http://i.imgur.com/tKtvlfj.png
Additional information: Invalid column name 'Username'.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ERegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*)from Employer where Username='" + TextBoxELUsername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select password from Employer where Username='" + TextBoxELUsername.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString().Replace(" ","");
if (password == TextBoxLoginPassword.Text)
{
Session["New"] = TextBoxELUsername.Text;
Response.Write("Password is Correct");
}
else
{
Response.Write("Password Incorrect");
}
}
else
{
Response.Write("Username Incorrect");
}
}
Your SQL is invalid. You forgot a space between the count(*) and from keyword. Try this instead:
select count(*) from Employer where Username=
Also you should change your sql to not allow sql injections and use the Parameters object
In the case of your Sql statement to retrieve the count(*) you really should Parameterize that statement to prevent sql injection.
string checkuser = #"select count(*)from Employer where Username= ?";
SqlCommand com = new SqlCommand(checkuser, conn);
comm.Parameters.AddWithValue("?", TextBoxELUsername.Text );
In addition try returning the variable temp in this fashion.
int temp = (int)comm.ExecuteScalar();
Beyond that I would try creating a second connection contained within the IF statement. It may sound odd but that connection can be stripped out of memory before the IF statement is triggered and in turn the program has no idea what connection your are trying to open.
You could avoid a second connection all together by creating a single sql statement
string checkuser = #"select count(*)from Employer where Username= ? and password = ?";
SqlCommand com = new SqlCommand(checkuser, conn);
comm.Parameters.AddWithValue("?", TextBoxELUsername.Text );
comm.Parameters.AddWithValue("?", TextBoxLoginPassword.Text );
your count return will only exist is both the username and password are correct.
You may also want to use the following code to force case sensitivity on your query
alter database your_database collate Latin1_General_CS_AS