Hi I am creating basic form in Visual Studio 2012 Express. I am using Microsoft Access 2012 as database. My problem is when I press submit button I nothing happens.
Syntax error in INSERT INTO statement.
System.Data.OleDb.OleDbErrorCollection
My code is given below. Please help me to resolve this issue.
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Desktop\del\SHAFI\db.accdb";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd = con.CreateCommand();
string text = "INSERT INTO TEST (Number, Amount) VALUES (?, ?)";
cmd.CommandText = text;
try
{
con.Open();
cmd.Parameters.AddWithValue("#Number", txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", txtOrder.Text);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
txtAmount.Text = "Sorry";
Response.Write(ex.Message.ToString() + "<br />" + ex.Errors.GetType());
}
}
Your code is correct, apart from the lacking of using statement around disposable objects, but the real problem is the word NUMBER. It is a reserved keyword for MSAccess.
Use it enclosed in square brackets.
string text = "INSERT INTO TEST ([Number], Amount) VALUES (?, ?)";
However, if it is still possible, I really suggest you to change that column name. This problem will become very annoying.
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Desktop\del\SHAFI\db.accdb";
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
string text = "INSERT INTO TEST ([Number], Amount) VALUES (?, ?)";
cmd.CommandText = text;
try
{
con.Open();
cmd.Parameters.AddWithValue("#Number", txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", txtOrder.Text);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
txtAmount.Text = "Sorry";
Response.Write(ex.Message.ToString() + "<br />" + ex.Errors.GetType());
}
}
OleDbCommand does not support named parameters. You have to add the parameters in the order you want them.
//Code above
con.Open();
cmd.Parameters.Add(txtAmount.Text);
cmd.Parameters.Add(txtOrder.Text);
cmd.ExecuteNonQuery();
//Code below
You are using #Number and #Amount variables for Number and Amount but not writing these values in query.
? used in java not in asp.net(c#). so you are mixing these two.
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Desktop\del\SHAFI\db.accdb";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd = con.CreateCommand();
string text = "INSERT INTO TEST (Number, Amount) VALUES (#Number, #Amount)";
cmd.CommandText = text;
try
{
con.Open();
cmd.Parameters.AddWithValue("#Number", txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", txtOrder.Text);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
txtAmount.Text = "Sorry";
Response.Write(ex.Message.ToString() + "<br />" + ex.Errors.GetType());
}
}
You should use:
string text = "INSERT INTO TEST (Number, Amount) VALUES (#Number, #Amount)";
instead of:
INSERT INTO TEST (Number, Amount) VALUES (?, ?)
Related
This code will perfectly retrieve data if there are no conditional clauses
(a basic select * from table statement), but it fails when I provide username and order by clause
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());
string cname = TextBox2.Text;
Session[cname] = cname.ToString();
con.Open();
string sql = " select * from customer_reservations where customer_id='"
+ Session[cname] + "' order by reservation_time ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
/*"select *from customer_reservations where customer_id='" + cname +
"' order by reservation_time";
*/
/* select *from customer_reservations */
}
The reservation_time is stored as datetime data type in SQL Server and does seem accessible because when I do a select * statement it does convert 14' O clock to 2pm in browser
Ok, is cname text, or a number? You have to check the database.
However, it always VERY easy to mess up string concatenation, and thus I suggest this:
protected void Button1_Click(object sender, EventArgs e)
{
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString()))
{
string cname = TextBox2.Text;
Session["cname"] = cname.ToString();
con.Open();
string sql = " select * from customer_reservations where customer_id = #cname "
+ " order by reservation_time";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#cname", SqlDbType.NVarChar).Value = cname;
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
So, it tends to be easier to write out the sql without all those quotes and what not. And bonus is we get sql injection safe code.
So try above.
Also, check your on-page load event. If it loads up the grid, or does anything, then you ALWAYS, but ALWAYS want to ONLY have code run on first page load, and hence this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
As a FYI, you would have needed this:
Session["cname"] = cname;
And to get the value out, you need this:
some var = Session["cname"].ToString();
You actually creating a session var of the actual text value!! - not something called "cname".
2nd FYI:
If you want to use paging on the grid, then you can't give the GV a "reader", and thus you need/should use this:
string sql = " select * from customer_reservations where customer_id = #cname "
+ " order by reservation_time";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#cname", SqlDbType.NVarChar).Value = cname;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I have an issue with the connectionstring or something similiar I assume. since data is printed from DB but won't write to DB using the INSERT Query string.
here's the .cs code part:
protected void Page_Load(object sender, EventArgs e)
{
Load_Data();
}
protected void Load_Data()
{
DataTable dtUsers = new DataTable();
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create sql
string sql = "SELECT Username, Fullname, Email FROM Users;";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// load data to dt
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtUsers.Load(reader);
con.Close();
// print data to gridview
GridView1.DataSource = dtUsers;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create query
string sql = "INSERT INTO Users (UserName,Passowrd,Email,FullName) VALUES ('" + txtUsername.Text + "','"+ txtPwd.Text + "','"+ txtEmail.Text + "','" + txtFullName.Text + "');";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// save data to db
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
thank you!
Here is ehat I try to do
on button_click I read the values from the text boxes and insert them in them in the database.
as tourist number for example maybe two or three tourists with ExecuteScalar; i get the ids of teh tourists which are inserted!
public void cmdInsert_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
string numtourist = (string)Session["tourist_number"];
for (int i = 0; i < Int32.Parse(numtourist); i++)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx888_1 = (TextBox)FindControl("txtMidNameK" + i.ToString());
TextBox tx888_2 = (TextBox)FindControl("txtLastNameK" + i.ToString());
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += " VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir", tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir", tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir", tx888_2.Text);
int added;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
lblproba.Text = "";
Tourist.Add(added);
lblproba.Text += Tourist.Count();
}
catch (Exception ex)
{
lblproba.Text += ex.Message;
}
finally
{
con.Close();
}
}
createReservation();
}
}
I call CreateReservationFunction AND i CREATE A NEW RESERVAION WITH THE ID OF THE USER WHO HAS MADE THE RESERVATION. wITH SELECT IDENTITY I TRY TO GET THE RESERVATION_ID of the reservation and here I get the exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack". So I wonder can this exception has something commn with the fact that in my solution exceptthe asp.net web projectI got library class in which I has .edmx file The entity framework model of my database and in my last form I don't use Ado,net but Entity framework
public void createReservation()
{
string insertSQL = "Insert INTO RESERVATIONS (User_ID) values (#User_ID) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#User_ID", 9);
try
{
con.Open();
string added = cmd.ExecuteScalar().ToString();
createTouristReservation(added);
}
catch (Exception ex)
{
lblproba.Text+= ex.Message;
}
}
Don't use ##IDENTITY but SCOPE_IDENTITY and add a semicolon between the insert and the select.
string insertSQL = #"INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)
VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir)
;SELECT CAST(scope_identity() AS int)";
I have built a custom validator,
I have a sql query like this:
protected void custom_serverValidate(object sender, ServerValidateEventArgs e)
{
connect();
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress=" + REmailTextBox.Text;
SqlCommand cmd = new SqlCommand(strSQL, objConnection);
if (e.Value.ToString() == cmd.ExecuteScalar().ToString())
{
e.IsValid = false;
}
else
e.IsValid = true;
disConnect();
}
when I execute my code in the browser and an email address and submit it , I get the error mentioned in the title. how to fix it ?
You are missing quotes around your email address. However - this is a SQL injection attack waiting to happen. Please switch to using a parameter.
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress = #EmailAddress"
...
cmd.Parameters.AddWithValue("#EmailAddress", REmailTextBox.Text);
You forgot to use the single quotes. Use:
string commandText = "select EmailAddress from Accounts_Users where EmailAddress=#EmailAttress";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add("#EmailAddress", REmailTextBox.Text);