Here is the cs file:
public int CheckExisting(String sqlDbQry, String sTable)
{
Qry = sqlDbQry;
con = new OleDbConnection(connectionstr);
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
cmd = new OleDbCommand(Qry, con);
dr = cmd.ExecuteReader();
while (dr.Read())
rQry = Convert.ToInt32(dr[0].ToString());
con.Close();
return rQry;
}
Here is my another cs:
protected void btnsub_Click(object sender, EventArgs e)
{
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Email='" + Textemail.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Your EmailId already Registered, Please Login!";
return;
}
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Phone_num='" + Textphone.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Mobile number already exists, Please Login!";
return;
}
}
When i enter input details and hit submit, it shows error something like this,
Here is the error of Screenshot
Can anyone help me to fix this?
You are manually building a sql string from a textbox labeled "email". Email addresses usually contain an "#". Because you are building a raw sql query you are putting the "#" directly in to the query. OleDb interprets that as a SQL parameter, and expects you to supply it, which you are not, which is what is causing the error. You will get a similar error if any of your text boxes contain a ' (single quote).
You should look in to using OleDbCommand and OleDbParameter to pass in your parameters instead of sending raw strings. This will also fix your sql injection attack vulnerability that others have mentioned.
I can't edit your post so I'm doing it here.
public int CheckExisting(String sqlDbQry, String sTable)
{
try
{
Qry = sqlDbQry;
con = new OleDbConnection(connectionstr);
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
cmd = new OleDbCommand(Qry, con);
dr = cmd.ExecuteReader();
while (dr.Read())
rQry = Convert.ToInt32(dr[0].ToString());
con.Close();
return rQry;
}
catch (OleDbException ex)
{
string message = ex;
//put your message on a texbox or alert handler error on the web
//or while debugging use a breakpoint on the exception handler
//use log
Console.WriteLine(message);
}
}
Keep in mind that with OleDb, parameters are positional, not named. You can name your parameters, but you cannot use the # syntax in your command (it throws an error about needing to declare a scalar variable) ... the correct syntax is to use the ? ... and it will take the parameters in the order in which you've added them.
Also, I prefer the .AddWithValue syntax, which is even more readable, I think.
protected void btnsub_Click(object sender, EventArgs e)
{
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Email='" + this.Textemail.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Your EmailId already Registered, Please Login!";
return;
}
if (objAdmin.CheckExisting("SELECT COUNT(*) FROM registration where Phone_num='" + this.Textphone.Text.Trim() + "'", "Temp") > 0)
{
lblmail.Text = "Mobile number already exists, Please Login!";
return;
}
}
Just put this.Textemail.Text and this.Textphone.Text , i hope so it will be helpful for you.
Related
I didn't encounter this error when my database was offline. I have just made my database online with db4free.net.
Everytime I log in this error occurs. Can somebody point out what's wrong?
private void btnLogIn_Click(object sender, EventArgs e)
{
string query = "select * from tbl_accounts where username='" + tbxUsername.Text + "' and password='" + tbxPassword.Text + "'";
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataAdapter da = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
try
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
if (dt.Rows.Count > 0)
{
employee_id = (dr["employee_id"].ToString().PadLeft(4, '0'));
fullname = (dr["account_firstname"] + " " + dr["account_lastname"]).ToString();
this.Invoke(new Action(() =>
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
this.Close();
th = new Thread(openNewForm);
th.SetApartmentState(ApartmentState.STA);
th.Start();
}));
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is the error:
Updated:
Here is my connection string:
MySqlConnection connection = new MySqlConnection("datasource=db4free.net;Convert Zero Datetime=True;SslMode=none");
Almost exactly 1 year to the date of the OP, I came across the same error experimenting with NuGet package MySQL.Data
I found the workaround within the comments of this earlier StackOverflow post
Basically, you can avoid the error by adding OldGuids=True; as part of your MySQL DB connection string as mentioned by #noontz.
However, as pointed out by #BradleyGrainger, be aware that by doing this, any BINARY(16) column will then be returned as a Guid rather than byte[].
Given your error happens here, your problem happens before this:
da.Fill(dt);
And you have two database fields and two controls
Thus your issue is likely with one of the two database fields (username or password)
I presume the username is a varchar or something
Therefore your password is likely a GUID
Conclusion:
You should probably format the value pulled from tbxPassword.Text to be a GUID.
And, as stated above, you'll want to protect against SQL injection too.
With the code below, I can insert the selected values of the checkboxes into a single line in the database.In the same line, it is added the date, a note, and an Id number from another table (not unique). In my .aspx page there is a simple treenode-checkboxes structure.
Now, I want to insert each selected value from the checkbox in his own line in the database table.
For example: 3 checkboxes are selected: 3 lines with each own value inserted (plus the same date, note, Id for all of them) in the database.
Please any ideas how to do it?
protected void btn_vac_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["pa_id"]);
string vn = string.Empty;
if (TreeView1.CheckedNodes.Count > 0)
{
foreach (TreeNode node in TreeView1.CheckedNodes)
{
vn += string.Format("{0}", node.Text);
}
}
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
if (note_vac.Text.Length != 0)
{
string insert_emer = "insert into P_vaccines (V_name,P_Id,Note,Date) values (#vn,#p_id,#note,#Date) ";
SqlCommand com = new SqlCommand(insert_emer, conn);
com.Parameters.AddWithValue("#vn", string.Format("{0}", vn));
com.Parameters.AddWithValue("#p_id", id);
com.Parameters.AddWithValue("#note", note_vac.Text);
com.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
com.ExecuteNonQuery();
}
else
{
string insert_emer = "insert into P_vaccines (V_name,P_Id,Date) values (#vn,#p_id,#Date) ";
SqlCommand com = new SqlCommand(insert_emer, conn);
com.Parameters.AddWithValue("#vn", string.Format("{0}", vn));
com.Parameters.AddWithValue("#p_id", id);
com.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
com.ExecuteNonQuery();
}
Response.Write("<script>alert('Success!')</script>");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error :" + ex.ToString());
}
}
You code could be simplified a lot. First, you should prepare the command before entering the foreach loop over the checked indices. This means, creating the connection and the command then inside the loop just update the values of the parameters that need to change. Something like this.
protected void btn_vac_Click(object sender, EventArgs e)
{
if (TreeView1.CheckedNodes.Count > 0)
{
try
{
string insert_text = "insert into P_vaccines (V_name,P_Id,Note,[Date]) values (#vn,#p_id,#note,#Date) ";
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
using(SqlCommand com = new SqlCommand(insert_text, conn))
{
com.Parameters.Add("#vn", SqlDbType.NVarChar);
com.Parameters.Add("#p_id", SqlDbType.Int).Value = Convert.ToInt32(Session["pa_id"]);
com.Parameters.Add("#note", SqlDbType.NVarChar);
com.Parameters.Add("#Date", SqlDbType.NVarChar).Value = DateTime.Now.ToShortDateString();
conn.Open();
foreach (TreeNode node in TreeView1.CheckedNodes)
{
com.Parameters["#vn"].Value = node.Text;
com.Parameters["#note"].Value = note_vac.Text.Length > 0 ? note_vac.Text : DbNull.Value;
com.ExecuteNonQuery();
}
}
Response.Write("<script>alert('Success!')</script>");
}
catch (Exception ex)
{
Response.Write("Error :" + ex.ToString());
}
}
}
Your original problem was caused by the vn +=... statement that concatenates together all the checked nodes. In this code instead I change that value directly on the Parameter with the value of the current check.
Note also that I have removed the AddWithValue calls that is known to be pretty a bad practice. But this means that you should be precise on the datatype of the values that you pass to your database engine. For example that datetime passed as string is a lot suspicious.
I should also add that having a column named Date is very confusing because there is a DataType with that name and if you want to use that column name it is better to encapsulate it with square brackets to avoid Syntax errors (or rename the column)
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=VIVID-PC;Integrated Security = True;Database=SchoolDb");
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
myConnection.Open();
string firstText = TextBox1.Text;
string SecondText = TextBox2.Text;
string thirdText = TextBox3.Text;
string fourthText = TextBox4.Text;
myCommand = new SqlCommand("INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)values('" + firstText + "','" + SecondText + "' , '" + thirdText + "','" + fourthText + "')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
Use command with parameters to pass data to server.
Make sure you dispose connection and command (via using statement)
Store connection strings in config file
Do not create dummy command objects
Here is complete code:
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText =
#"INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)
VALUES (#studentName, #rollNo, #session, #mobileNo)";
command.Parameters.AddWithValue("studentName", TextBox1.Text);
command.Parameters.AddWithValue("rollNo", TextBox2.Text);
command.Parameters.AddWithValue("session", TextBox3.Text);
command.Parameters.AddWithValue("mobileNo", TextBox4.Text);
connection.Open();
try
{
command.ExecuteNonQuery();
}
catch(SqlException e)
{
if (e.Message.Contains("Violation of UNIQUE KEY constraint"))
// you got unique key violation
}
}
Further considerations - improve naming in your code - TextBox1, TextBox2 etc says nothing to reader. Give them appropriate names, like StudentNameTextBox, RollNoTextBox etc. Also good practice is splitting data access and UI logic.
If the database detects a unique key violation, this line
myCommand.ExecuteNonQuery();
will throw an exception. You can catch that exception and proceed with your own code:
try
{
myCommand.ExecuteNonQuery();
}
catch(Exception e)
{
// right here, "something" went wrong. Examine e to check what it was.
}
Please note that your code is vulnerable to SQL injection attacks. You should be using command paramaters instead of building the SQL manually. In addition, you should be using using blocks (see here for details)
ExecuteNonQuery will throw an exception if it's unable to INSERT row into database. In your case, it's most likely an SqlException. Catch it.
use your returnType from ExecuteNonQuery() (Read the remarks part) to detect failure in insertion. you can use the exception or the no. of rows affected part
Try this :
try
{
... your rest of the code
...
int rowsAffected = myCommand.ExecuteNonQuery(); // Most probaboly it will throw exception in case of Unique key violation. If not, still no rows have been affected
if(rowsAffected<1)
{
//your Alert for no records inserted
}
else
{
//your alert for successful insertion
}
}
catch(SqlException ex)
{
//check the exception and display alert
}
finally
{
//release connection and dispose command object
}
As suggested in comment use command param.
try
{
//Your other code
_myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
catch(SqlException sqlExc)
{
// Your popup or msg.
}
You also loop for different sql error in catch block.
So I have this code that is designed to delete a row in mySQL server database judging by what is selected in my list box. Here is the code I have to remove the rows:
private void remove_btn_Click(object sender, EventArgs e)
{
try
{
if (Calls_lsb.SelectedItem == null)
MessageBox.Show("Please select an item for deletion.");
}
else
{
int i = Calls_lsb.SelectedIndex;
if (i > 0)
{
SqlConnection connection = new SqlConnection(//My Connection String);
string sqlStatement1 = "DELETE FROM Records WHERE CallID = #Id";
string sqlStatement2 = "DELETE FROM Calls WHERE CallID = #Id";
connection.Open();
SqlCommand cmd1 = new SqlCommand(sqlStatement1, connection);
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd1.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand(sqlStatement2, connection);
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd2.ExecuteNonQuery();
connection.Close();
Calls_lsb.Items.Remove(Calls_lsb.Items[i]);
}
else
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I get no exceptions and I have similar code that adds records that works fine. I tried stepping into the code but it all seemed fine. It simply just does not delete the row from the database. It removes the correct item from the list, just not the database.
If anyone could shine some light on this situation that would be great, thanks!
Edit : Ok, I seem to have fixed the problem. I just removed the whole i = selected index stuff and replace the 'Calls_lsb.Items[i]' with '(Calls_lsb.SelectedIndex + 1)'. I don't really understand why I was getting an exception when I tried to add 1 to i as this is basically doing the same thing.
Replace your below line code.
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
//with
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
and
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
// with
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
I'm trying to get my login system to work. Currently I think I have everything in place for it to work except the if statement conditions (if row is returned, then if statement is true, else login unsuccessful). I'm not sure how to read in the number of rows returned, I did attempt to use the ExecuteReader Method but couldn't get it to work.
Appreciate any help, thanks.
Code:
private void btn_login_Click(object sender, EventArgs e)
{
SqlCeConnection connection = new SqlCeConnection(#"Data Source=C:\\temp\\Project\\WindowsFormsApplication2\\Database.sdf");
connection.Open();
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Technician WHERE Name = '" + txt_username.Text + "' AND Password = '" + txt_password.Text + "' ");
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
if ()
{
MessageBox.Show("Login Successful");
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));
t.Start();
this.Close();
}
else
{
MessageBox.Show("Login Unsuccessful");
return;
}
connection.Close();
}
I have changed your code to use a simpler ExecuteScalar that returns the first column of the first row obtained by your query
Of course, it is of extreme importance that you don't write your sql commands concatenating strings because this could fail in spectacular ways. (What if your textboxes contains a single quote and what if your user writes malicious text like this
using(SqlCeConnection connection = new SqlCeConnection(.....))
{
connection.Open();
string sqlText = "SELECT Count(*) FROM Technician WHERE Name = #name AND Password=#pwd"
SqlCeCommand command = new SqlCeCommand(sqlText, connection);
command.Parameters.AddWithValue("#name", txt_username.Text);
command.Parameters.AddWithValue("#pwd", txt_password.Text);
int result = (int)command.ExecuteScalar();
if (result > 0)
{
MessageBox.Show("Login Successful");
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));
t.Start();
this.Close();
}
else
{
MessageBox.Show("Login Unsuccessful");
return;
}
}
Notice also the using statement, in your previous code you exit from the procedure if no login is found but you forget to close the connection. This could become a big problem during lifetime of your application. The Using statement prevents this
Now I should start talking about the weakness of storing and trasmitting passwords in clear text, but that is another matter
The method ExecuteNonQuery will return the number of rows affected.
int rowsAffected = command.ExecuteNonQuery();
bool userExists = rowsAffected > 0;
if (userExists) // The user exists
{
}
Note: However your application is vulnerable to SQL Injection. I.e. I could enter ;DROP TABLE Technician into the txt_password text box.
You should use a parameterized query instead or another authentication method which is more secure (ASP.NET membership for instance).
To use paramertised queries you can change the CommandText to:
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Technician WHERE Name=#username AND password=#password";
And then add the parameters in via:
command.Parameters.AddWithValue("#username", txt_username.Text);
command.Parameters.AddWithValue("#password", txt_password.Text);
http://johnhforrest.com/2010/10/parameterized-sql-queries-in-c/
private void btn_login_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=C:\\temp\\Project\\WindowsFormsApplication2\\Database.sdf");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Technician WHERE Name = '" + txt_username.Text + "' AND Password = '" + txt_password.Text + "' ");
int row=command.ExecuteNonQuery();
if (row>0)
{
MessageBox.Show("Login Successful");
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));
t.Start();
this.Close();
}
else
{
MessageBox.Show("Login Unsuccessful");
return;
}
connection.Close();
}
a=1;
b=1;
if a=b
{
a=c;
}
else
{
a=b;
}
else if
{
MessageBox.Show("Login Unsuccessful");
return i;