How to managed two sql queries in ASP.Net (Visual Studio 2010) - asp.net

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();

Related

Syntax error in INSERT INTO statement. System.Data.OleDb.OleDbErrorCollection

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 (?, ?)

Insert data into database in ASP.NET throwing exception

I'm trying to insert data into database in ASP.NET with this code:
string conn = "TJLDatabaseConnectionString";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption) Values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')", objsqlconn);
objcmd.ExecuteNonQuery();
//MessageBox.Show("Successful");
But when I run it. It gives the following message:
First the important, always use sql-parameters to prevent sql-injection. Never concatenate parameters into a sql-query. This can also solve localization or "escaping" issues.
Also, use the using statement to ensure that anything using unmanaged resources (like a sql-connection) will be closed and disposed even on error:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption)";
using(var objsqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
using (var cmd = new SqlCommand(sql, objsqlconn))
{
cmd.Parameters.AddWithValue("#MachineName", TextBox1.Text);
cmd.Parameters.AddWithValue("#LastReading", TextBox2.Text);
cmd.Parameters.AddWithValue("#CurrentReading", TextBox3.Text);
cmd.Parameters.AddWithValue("#Consumption", TextBox4.Text);
objsqlconn.Open();
int insertedCount = cmd.ExecuteNonQuery();
}
Side-note: if you have an identity column and you want to retrieve the newly created primary-key, use SCOPE_IDENTITY and ExecuteScalar even if you use INSERT INTO:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption);
SELECT CAST(scope_identity() AS int)";
//...
int newID = (int)cmd.ExecuteScalar();
Use a variable to check if row is getting affected or not
rowAffected= objcmd.ExecuteNonQuery();
if(rowAffected >0)
{
//sucessful
}
else
{
//
}
Since there is no any exception mention in your question so just for a better and readable code I would suggest you too use using blocks. It gives you nice, cleaner and readable code and also handle objects when they go out of scope.
This is meant for good practices that we generlly follow while coding. Kindly show us the exception for appropriate solution.
private void ConnectToDb()
{
var conn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using( var conn = new SqlConnection(conn))
{
conn.Open();
var cmdtxt ="Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption)
Values(#P1,#P2,#P3,#P4)";
using(var cmd = new SqlCommand(cmdtxt, conn))
{
cmd.CommandType=CommandType.Text;
cmd.Parameters.AddWithValue("#P1", TextBox1.Text);
cmd.Parameters.AddWithValue("#P2", TextBox2.Text);
cmd.Parameters.AddWithValue("#P3", TextBox3.Text);
cmd.Parameters.AddWithValue("#P4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
con.close();
}
}

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when I use scope identity

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)";

what is wrong with this C# duplicate row code?

I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct

Insert ADO.Net DataTable into an SQL table

The current solution i implemented is awful!
I use a for... loop for inserting records from an ADO.NET data-table into an SQL table.
I would like to insert at once the data-table into the SQL table, without iterating...
Is that possible, or am i asking too much?
You can pass the entire DataTable as a single Table Valued Parameter and insert the entire TVP at once. The following is the example from Table-Valued Parameters in SQL Server 2008 (ADO.NET):
// Assumes connection is an open SqlConnection.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(
DataRowState.Added);
// Define the INSERT-SELECT statement.
string sqlInsert =
"INSERT INTO dbo.Categories (CategoryID, CategoryName)"
+ " SELECT nc.CategoryID, nc.CategoryName"
+ " FROM #tvpNewCategories AS nc;"
// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(
sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
"#tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.CategoryTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
}
TVP are only available in SQL 2008.
I think you are looking for SQLBulkCopy.
SqlBulkCopy is the simplest solution.
using (SqlConnection dbConn = new SqlConnection(connectionString))
{
dbConn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dbConn))
{
bulkCopy.DestinationTableName =
"dbo.MyTable";
try
{
bulkCopy.WriteToServer(myDataTable, DataRowState.Added);
}
catch (Exception ex)
{
myLogger.Error("Fail to upload session data. ", ex);
}
}
}
You can create SqlBulkCopyColumnMapping if the columns in your DataTable don't match your database table.
You can also try the following method.
private void button1_Click(object sender, EventArgs e)
{
tabevent();
DataSet ds = new DataSet();
DataTable table = new DataTable("DataFromDGV");
ds.Tables.Add(table);
foreach (DataGridViewColumn col in dataGridView1.Columns)
table.Columns.Add(col.HeaderText, typeof(string));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
table.Rows.Add(row);
foreach (DataGridViewCell cell in row.Cells)
{
table.Rows[row.Index][cell.ColumnIndex] = cell.Value;
}
}
// DataTable ds1changes = ds1.Tables[0].GetChanges();
if (table != null)
{
SqlConnection dbConn = new SqlConnection(#"Data Source=wsswe;Initial Catalog=vb;User ID=sa;Password=12345");
SqlCommand dbCommand = new SqlCommand();
dbCommand.Connection = dbConn;
foreach (DataRow row in table.Rows)
{
if (row["quantity"] != null && row["amount"]!=null && row["itemname"]!=null)
{
if (row["amount"].ToString() != string.Empty)
{
dbCommand.CommandText =
"INSERT INTO Bill" +
"(Itemname,Participants,rate,Quantity,Amount)" +
"SELECT '" + Convert.ToString(row["itemname"]) + "' AS Itemname,'" + Convert.ToString(row["Partcipants"]) + "' AS Participants,'" + Convert.ToInt32(row["rate"]) + "' AS rate,'" +
Convert.ToInt32(row["quantity"]) + "' AS Quantity,'" + Convert.ToInt32(row["amount"]) + "' AS Amount";
dbCommand.Connection.Open();
dbCommand.ExecuteNonQuery();
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
MessageBox.Show("inserted");
}
}
}
}
}

Resources