what is wrong with this C# duplicate row code? - asp.net

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

Related

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

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

Delete from command not working in sqlite?

I have a sqlite db file. I am using DB Browser for Sqlite as the client. I went in and ran delete from command on most of my tables. Thereafter I tried to export using the option Database to SQL file I notice all my data is appearing in it. What I wondering is that why the data have not been deleted? I know the sqlite file size will not shrink.
Below is snippet of my codes.
string str = #"Data Source=" + userFilePath + "\\mysqlite.sqlite3";
using (SQLiteConnection con = new SQLiteConnection(str))
{
con.Open();
SQLiteTransaction trans = con.BeginTransaction();
try
{
String cmdSelect1 = "Select * from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
int fiscalPeriod = Convert.ToInt32(monthNumber);
int financialYear = Convert.ToInt32(itemvalueyear);
using (SQLiteCommand cmd1 = new SQLiteCommand(cmdSelect1, con, trans))
{
SQLiteDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Records Already Exist ? Are you confirm replace it?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
String deleteTable = "Delete from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
using (SQLiteCommand cmdDeleteTb1 = new SQLiteCommand(deleteTable, con, trans))
{
cmdDeleteTb1.ExecuteNonQuery();
cmdDeleteTb1.Dispose();
}
foreach (object line in linesC)
{
if (line.GetType() == typeof(TypeC))
{
String cmdText2 = "INSERT INTO table1(tbID,companyID,month,year) VALUES(#tbID,#companyID,#month,#year)";
using (SQLiteCommand cmd = new SQLiteCommand(cmdText2, con, trans))
{
cmd.Parameters.AddWithValue("#tbID", tbID);
cmd.Parameters.AddWithValue("#companyID", companyID);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#year", year);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
}
}
}
}
}
dr1.Close();
cmd1.Dispose();
}
trans.Commit();
MessageBox.Show("Successfully Inserted Into Database");
}
catch (Exception ex)
{
MessageBox.Show("Rollback " + ex.ToString());
trans.Rollback();
}
con.Close();
con.Dispose();
GC.Collect();
Ok:
It appears you are beginning two transactions. You begin your loop inserts after you begin your delete.
Commit your Delete transaction and then later commit your inserts.
This is than committing after beginning both transactions.

Data is not inserted into database using windows application but not showing any error

Button Click Code
String cs = null;
SqlConnection scon = null;
SqlCommand cmd = null;
private void btnOk_Click(object sender,EventArgs e)
{
String name = txtBoxName.Text.ToString();
String mobile = txtBoxMobile.Text.ToString();
String address = txtBoxAddress.Text.ToString();
String ty = null;
if (radioButtonCow.Checked)
{
ty = radioButtonCow.Text.ToString();
}
else {
ty = radioButtonBuffalo.Text.ToString();
}
int n = 0;
using(scon = new SqlConnection(cs)){
scon.Open();
String query = "insert into new_customer(name,mobile,address,type)
values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";
cmd = new SqlCommand(query, scon);
n = cmd.ExecuteNonQuery();
}
}
private void NewCustomer_Load(object sender, EventArgs e)
{
cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
}
}
When I run this application it runs successfully without showing any error but it doesn't insert any records in the table. The table has the fields id, name, mobile, address and type. id is a primary key and it's an identity field. All the other fields are of varchar type.
Why doesn't it insert data in the table?
You just pass your parameters in this way as i mentioned below,
SqlConnection scon = new SqlConnection(cs);
scon.Open();
String query = "insert into new_customer values(#name,#mobile,#address,#type)";
cmd = new SqlCommand(query, scon);
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#name",mobile);
cmd.Parameters.AddWithValue("#name",address);
cmd.Parameters.AddWithValue("#name",ty);
cmd.ExecuteNonQuery();
scon.Close();
try by wrap the type field as [type]
String query = "insert into new_customer(name,mobile,address,[type]) values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";

Login Page to verify NIC number

I am facing the followingj problem: I have a database on Access 2010 with fields NIC,Active and Page, all are of number types. I want to create a login page that takes NIC (numeric) as an input from the user and then redirects them to specific page as per their NICs.
Different people will see different pages.. I am getting an error in ExecuteScalar command, maybe my query is not correct or maybe ExecuteScalar can't hold the query... I am getting data type mismatch error.
try
{
FirsstPage f = new FirsstPage();
SecondPage second = new SecondPage();
oledcon.Open();
string NIc = ( TextBox1.Text);
// string query = "select * from LogINTable where NIC='" + NIc + "'AND Active=0 AND page=1";
//string query = "select * from LogINTable where NIC='" + nic + "'AND Active=0";
string query = "SELECT * FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1";
//string query = "select
OleDbCommand comm = new OleDbCommand( query,oledcon);
string a = (string) comm.ExecuteScalar();
if (a != null)
{
Response.Redirect("FirsstPage.aspx");
string update = "update into LogINTable Active='1' where NIC='" + NIc + "' ";
//OleDbCommand com = new OleDbCommand();
//int b = Convert.ToInt32( com.ExecuteScalar());
}
else
{
Response.Redirect("SecondPage.aspx");
string update = "update into LogINTable Active='1' where NIC='" +NIc + "' ";
}
oledcon.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
oledcon.Close();
}
Problem is that you are using ExecuteScalar with wrong query.
string a = (string) comm.ExecuteScalar();
ExecuteScalar() will return single value as a result from query.
Please change your query to the query like blow which return single value from database in place of entire colomn
Select NIC FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1"
Source :http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
I hope it will help you.

SqlException in Asp.net - Incorrect syntax near 'Van'

I have problem with my SqlCommand everything I open the page I get the error:
System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'.
I cannot find the problem because 'Van' is only found once in the entire project, and in the title..
This is my code in the Page_Load:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
}
The database connectionstring is correct because it works for all my other pages.. i'm trying to get the department where an employee works so he/she can only view memo's from their own department.
You need to close the parentheses after the last name provided.
SELECT (SELECT Memo_ID, Dep_Name FROM Department
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx' )
Here is what it should look like:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
You need to quote the last name. You probably want to convert to a parameterized query too.
I'd have expected your WHERE clause to wrap the User.Identity.Name in quotes:
WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ...
Could "van" be in the username?
This isn't a very secure query either - but SQL injection's another issue!

Resources