error insert query after install application - c#

i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me

You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}​

Related

MySQL update +- amount

I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}

Unable to save data into database

I am inserting some data into database using run-time SQL query, but before that i am checking is there any record exists or not. following is my code
protected void btnSignUp_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
string strgender = "";
if (Rb_Male.Checked)
strgender = "Male";
else if (Rb_Female.Checked)
strgender = "Female";
else
{
lblMsg.Text = "Please Select Gender";
lblMsg.ForeColor = Color.Red;
}
con.Open();
SqlCommand cmdcheck = new SqlCommand();
cmdcheck.CommandText = "select * from [Users] where E_Mail='" + #tb_Email.Text + "'";
cmdcheck.Connection = con;
//cmd.Parameters.AddWithValue("#em", tb_Email.Text);
SqlDataReader drd = cmdcheck.ExecuteReader();
if (drd.Read())
{
lblEmail.Visible = true;
lblEmail.Text = "Email Already Exsits";
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
else
{
string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')";
SqlCommand cmd = new SqlCommand(strcmd, con);
cmd.ExecuteNonQuery();
lblMsg.Text = "Account created sussecfully";
lblMsg.ForeColor = Color.Green;
clearallfields();
}
}
}
catch
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
}
else
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = " * Enter Required Field(s)";
}
}
The bellow part is working well in case if there no record associated with the particular email but if there is no record it goes to the else part and after executenonquery(); it goes to the catch part
if (drd.Read())
{
lblEmail.Visible = true;
lblEmail.Text = "Email Already Exsits";
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
else
{
string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')";
SqlCommand cmd = new SqlCommand(strcmd, con);
cmd.ExecuteNonQuery();
lblMsg.Text = "Account created sussecfully";
lblMsg.ForeColor = Color.Green;
clearallfields();
}
}
}
catch
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
kindly help me out with this..
Your insert statement doesn't specify which columns you want to add to the Users table.Place a breakpoint on the following line:
string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')";
Take the value of strcmd and execute it in SQL Server Management Studio.You will see that it most likely fails.Fix the insert statement unti it works in SQL then copy it in your ASP.NET web application.
Also change your catch block and inspect the exception you're getting:
catch(Exception ex)
{
System.Diagnostics.Debugger.Break();
}

CheckBox Not Sending Checked Value to Access Database C# Asp

This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";

C# Syntax error (missing operator) in query expression

I receive this error on cmd.ExecuteNonQuery()... I think I am wrong on cmd.CommandText...
Syntax error (missing operator) in query expression 'Nr_Crt='1' and Varsta '3' and KG '2' and Specie 'Iepure' and Risc'Nu' and Tip1 'Diurn' and Tip2 'Carnivor''.
private void button2_Click_1(object sender, EventArgs e)
{
if (txtNr_Crt.Text != " " & txtVarsta.Text != " " & txtKG.Text != " " & txtSpecie.Text != " " & txtRisc.Text != " " & txtTip1.Text != " " & txtTip1.Text != " " & txtTip2.Text != "")
{
cn.Open();
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta '" + txtVarsta.Text + "' and KG '" + txtKG.Text + "' and Specie '" + txtSpecie.Text + "' and Risc'" + txtRisc.Text + "' and Tip1 '" + txtTip1.Text + "' and Tip2 '" + txtTip2.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
txtNr_Crt.Text = "";
txtVarsta.Text = "";
txtKG.Text = "";
txtSpecie.Text = "";
txtSex.Text = "";
txtRisc.Text = "";
txtTip1.Text = "";
txtTip2.Text = "";
}
}
You code is vulnerable to SQL injection, i'd fix that.
The issue is that you are missing the = from each of your subsequent and's:
cn.Open();
cmd.Parameters.AddWithValue("#Nr_Crt", txtNr_Crt.Text);
cmd.Parameters.AddWithValue("#Varsta", txtVarsta.Text);
cmd.Parameters.AddWithValue("#KG", txtKG.Text);
cmd.Parameters.AddWithValue("#Specie", txtSpecie.Text);
cmd.Parameters.AddWithValue("#Risc", txtRisc.Text);
cmd.Parameters.AddWithValue("#Tip1", txtTip1.Text);
cmd.Parameters.AddWithValue("#Tip2", txtTip2.Text);
cmd.CommandText = "DELETE from Animale Where Nr_Crt= #Nr_Crt and Varsta = #Varsta and KG = #KG and Specie = #Specie and Risc = #Risc and Tip1 = #Tip1 and Tip2 = #Tip2";
cmd.ExecuteNonQuery();
cn.Close();
This should fix it (and the SQL injection risk)
Your query is wrong. You are missing = when comparing the columns
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta='" + txtVarsta.Text + "' and KG='" + txtKG.Text + "' and Specie='" + txtSpecie.Text + "' and Risc='" + txtRisc.Text + "' and Tip1='" + txtTip1.Text + "' and Tip2='" + txtTip2.Text + "'";
foreach(Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
ctrl.text="";
}
}
For cleaning all textbox at once :) you can create a Method that performs it when you need it

On load event problem

I have a problem when I want to update a row in a database. The page that updates also adds a client but the problem is that when page load detects update button was pressed it seems to keep loading up the variables and I am unable to update my database.
public partial class CustomerInput : System.Web.UI.Page
{
string update, Id, Name, Address, Suburb, Postcode, Age, Email;
protected void Page_Load(object sender, EventArgs e)
{
update = Request.QueryString["Update"];
if (update == "true")
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
Button1.Text = "Update";
Id = Request.QueryString["Id"];
connection.Open();
SqlCommand command = new SqlCommand("Select * from Customer where Id = " + Id, connection);
SqlDataReader read = command.ExecuteReader();
read.Read();
TextBox1.Text = read[1].ToString();
TextBox2.Text = read[2].ToString();
TextBox3.Text = read[3].ToString();
TextBox4.Text = read[4].ToString();
TextBox5.Text = read[5].ToString();
TextBox6.Text = read[6].ToString();
connection.Close();
update = string.Empty;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
if (Button1.Text == "Update")
{
connection.Open();
SqlCommand command;
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
command = new SqlCommand("UPDATE Customer SET Name = " + "'" + Name + "', " + "Address = " + "'" + Address + "', " + "Suburb = " + "'" + Suburb + "', "
+ "Postcode = " + "'" + Postcode + "', " + "Age = " + "'" + Age + "', " + "Email = " + "'" + Email + "' " + "Where Id =" + Id, connection);
command.ExecuteNonQuery();
connection.Close();
}
if (Button1.Text == "New Client")
{
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
Response.Write("Blah");
SqlCommand command = new SqlCommand("INSERT INTO Customer VALUES (" + "'" + Name + "'" + ", " + "'" + Address + "'" + ", " + "'" + Suburb + "'" + ", "
+ "'" + Postcode + "'" + ", " + "'" + Age + "'" + ", " + "'" + Email + "'" + ")", connection);
command.ExecuteNonQuery();
}
Button1.Text = "New Client";
}
}
}
At the start of your page load event you need to add an if statement to check if this is the first time the page loads:
example:
if (!IsPostBack)
{
... add your code here
}
I guess you need to use Page.IsPostBack:
if (Page.IsPostBack)
{
// Do Something ..
{
else
{
// Do something else ..
}

Categories

Resources