I am trying to run multiple queries within a loop. The first query runs ok as I can see it when I step through the code.
However the second query (which is within a loop) is supposed to run depending on the value held from the first. When the loop runs based on that value it seems to be ignoring the query. I put a label to display in place of the query and it displayed so I believe how I have opened/closed my connection is not correct.
c# code:
protected void Page_Load(object sender, EventArgs e)
{
// Get the session of the user
string staffid = Session["StaffId"].ToString();
//Proxy on page load to check IsActive Status
string DefaultConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(DefaultConnection);
myConnection.Open();
//select the userdetail specific to the logged in user using parameterisation
string query = "SELECT ProxyStatus.ProxyStatusId, ProxyStatus.FunctionId, ProxyStatus.StartDate, ProxyStatus.EndDate, ProxyStatus.IsActive FROM ProxyStatus INNER JOIN Staff ON Staff.StaffId = ProxyStatus.Proxee WHERE (Staff.StaffId = #StaffId)";
DateTime thisDay = DateTime.Today;
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#staffid", staffid);
SqlDataReader rdr = myCommand.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Session["StartDate"] = rdr["StartDate"].ToString();
Session["EndDate"] = rdr["EndDate"].ToString();
Session["ProxyStatusId"] = rdr["ProxyStatusId"].ToString();
Session["FunctionId"] = rdr["FunctionId"].ToString();
// Get the session of StartDate and endate, use the session value in a query to compare against the current date
string startdate = Session["StartDate"].ToString();
string enddate = Session["EndDate"].ToString();
string proxystatus = Session["ProxyStatusId"].ToString();
DateTime startdatedata = Convert.ToDateTime(startdate);
DateTime enddatedata = Convert.ToDateTime(enddate);
if (startdatedata > thisDay)
{
string DefaultConnection2 = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(DefaultConnection2);
myConnection2.Open();
string query2 = "UPDATE ProxyStatus SET ProxyStatus.IsActive = 'False' WHERE ProxyStatus.ProxyStatusId = #proxystatus";
myCommand.Parameters.AddWithValue("#newproxystatus", proxystatusnew);
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
}
}
}
else
{
rdr.Close();
}
}
}
}
Shouldn't the lines be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand.ExecuteNonQuery();
be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
instead? The first "myCommand" will still be in use with "rdr".
Related
I am trying to update a databse entry under a specific id in my table when the users enter their ID number in a textBox.
At the moment it updates but updates all entries in my table except the entry containing the users ID number.
This is the code I am currently using:
private void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123");
SqlCommand check_User_Name = new SqlCommand("SELECT Id FROM NewVisitor WHERE (IDNumber = #IDNumber)", con);
check_User_Name.Parameters.AddWithValue("#IDNumber", idNumber_TxtBox.Text);
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
var connetionString = #"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123";
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer";
try
{
using (var connection = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#PersonVisit", SqlDbType.NVarChar).Value = personVisiting_TxtBox.Text;
command.Parameters.Add("#PurposeVisit", SqlDbType.NVarChar).Value = purposeOfVisit_CMBox.SelectedItem;
command.Parameters.Add("#Duration", SqlDbType.Date).Value = duration_dateTimePicker1.Value.Date;
command.Parameters.Add("#Disclaimer", SqlDbType.NVarChar).Value = disclaimer_CHKBox.Checked;
connection.Open();
command.ExecuteNonQuery();
}
}
}
The whole table has many more fields but would like to just update the above fields within that specific ID.
Thanks
You forgot the WHERE clause on the UPDATE statement, telling it specifically which records to update. It sounds like you just want to add the exact same WHERE clause that you have on your SELECT:
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer WHERE (IDNumber = #IDNumber)";
And don't forget to add the paramter for it:
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber_TxtBox.Text;
You may need to convert the input value to an integer first, I'm not 100% certain (it's been a while since I've had to use ADO.NET directly). Something like this:
if (!int.TryParse(idNumber_TxtBox.Text, out var idNumber))
{
// input wasn't an integer, handle the error
}
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber;
im writing a library database program. It can insert books, but I have a problem in making a reference between book and a person which rents it. I can't get a last inserted id from a rents table to put it to the compilation table to assign book to a person who rents it. I've tried SCOPE_IDENTITY() but it doesn't works for me. Here's the code:
private void addRentButton_Click(object sender, EventArgs e) {
elibrary f1 = new elibrary();
string query = "INSERT INTO rents VALUES (#renterName, #rentStartDate, #rentEndDate)";
using(f1.Connection = new SqlConnection(f1.connectionString))
using(SqlCommand command = new SqlCommand(query, f1.Connection)) {
f1.Connection.Open();
command.Parameters.AddWithValue("#renterName", rentNameBox.Text);
command.Parameters.AddWithValue("#rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("#rentEndDate", rentEndDatePicker.Value);
command.ExecuteScalar();
}
rentEndDatePicker.Value = DateTime.Now;
string Compilationquery =" INSERT INTO compilation VALUES (#bookId, SELECT SCOPE_IDENTITY())";
using(f1.Connection = new SqlConnection(f1.connectionString))
using(SqlCommand command = new SqlCommand(Compilationquery, f1.Connection)) {
f1.Connection.Open();
command.Parameters.AddWithValue("#bookId", f1.listBook.SelectedValue);
command.ExecuteScalar();
Actually, you are not retrieving the last inserted ID value from the first query, since the SCOPE_IDENTITY() is wrongly placed and you are not assigning the ExecuteScalar() return value anywhere:
String query = "INSERT INTO rents VALUES (#renterName, #rentStartDate, #rentEndDate); SELECT CONVERT(INT, SCOPE_IDENTITY())"; // "SELECT CAST(SCOPE_IDENTITY() AS INT)" can also be an option
Int32 lastId = 0;
using (f1.Connection = new SqlConnection(f1.connectionString))
using (SqlCommand command = new SqlCommand(query, f1.Connection))
{
f1.Connection.Open();
command.Parameters.AddWithValue("#renterName", rentNameBox.Text);
command.Parameters.AddWithValue("#rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("#rentEndDate", rentEndDatePicker.Value);
lastId = (Int32)command.ExecuteScalar();
}
Once this is done, you can proceed with the second query as follows:
String compilationQuery = "INSERT INTO compilation VALUES (#bookId, #rentId)";
using (f1.Connection = new SqlConnection(f1.connectionString))
using (SqlCommand command = new SqlCommand(compilationQuery, f1.Connection))
{
f1.Connection.Open();
command.Parameters.AddWithValue("#bookId", f1.listBook.SelectedValue);
command.Parameters.AddWithValue("#rentId", lastId);
// ...
You have disposed the command so SCOPE_IDENTITY() is gone. There is no reason to dispose of the commmand twice.
using(SqlCommand command = new SqlCommand(query, f1.Connection))
{
f1.Connection.Open();
command.Parameters.AddWithValue("#renterName", rentNameBox.Text);
command.Parameters.AddWithValue("#rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("#rentEndDate", rentEndDatePicker.Value);
command.ExecuteScalar();
int id = (Int32)command.ExecuteScalar();
command.Parameters.Clear();
Compilationquery = "INSERT INTO compilation VALUES (#bookId, #id)";
command.CommandText = Compilationquery;
command.Parameters.AddWithValue("#bookId", f1.listBook.SelectedValue);
command.Parameters.AddWithValue("#id", id);
command.ExecuteScalar();
}
I Retrive values from admin table and then i store in String variable and finally i compare values my code is not redirect to another page
protected void Button1_Click(object sender, EventArgs e)
{
String uname = (String)txtuser.Text;
String upass = (String)txtp.Text;
String cuser = "";
String cpass = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HMSS"].ToString());
conn.Open();
String query = "select username,password from admin where username=#username";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("username", uname);
cmd.Parameters.AddWithValue("password", upass);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cuser = rdr["username"].ToString();
cpass = rdr["password"].ToString();
}
if (cuser==uname && cpass==upass)
{
Session["user"] = cuser;
Response.Redirect("admin.aspx",true);
}
}
}
Can you check following code lines?
String uname = (String)txtuser.Text;
(string) implicit cast is not necessary: Text property is already a string.
conn.Open();
missing conn.Close(); it's better to add also try/catch
String query = "select username,password from admin where username=#username";
cmd.Parameters.AddWithValue("password", upass);
why don't you check also password in the query?
cuser = rdr["username"].ToString();
It means null value not allowed
if (cuser==uname && cpass==upass)
Problem with case sensitive/trim. In debug do you arrive on Response.Redirect?
Response.Redirect("admin.aspx",true);
Maybe ~/admin.aspx
try to change your condition to below
if (cuser.ToLower() == uname.ToLower() && cpass.ToLower() == upass.ToLower())
Here is my situation. I want to perform paging, grouping and filtering. So that I am using page_init method. As per my code it's working fine. But user only can give where clause conditions like
For example, I have a textbox in my page. that textbox ID="txtQuery", in that textbox user will enter the where clause like itemID='45366' So i have to make my code like below
cmd.commandText="select * from TABLE_NAME where "+txtQuery.text
So this will show the records. This is the problem now. When I make cmd.commandText like above it throws an error
System.Data.SqlClient.SqlException: Incorrect syntax near 'where'.
If i give directly, It's working fine without any error.
This is my code
string whereQuery = "";
protected void Page_Init(object sender, EventArgs e)
{
// initialize SomeDataTable
if (IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
whereQuery = getWhereQuery();
//Response.Write("<br/><br/><br/><br/>" + whereQuery);
using (SqlConnection con = new SqlConnection(cs))
{
string query = #"select transactions.storeid as StoreID, YEAR(transactions.Time) Year, MONTH(transactions.Time) Month,
transactionsEntry.TransactionNumber,transactionsEntry.Quantity,
items.ItemLookupCode,items.DepartmentID,items.CategoryID,items.SubDescription1,
suppliers.SupplierName,suppliers.Code
FROM [HQMatajer].[dbo].[Transaction] as transactions
RIGHT JOIN [HQMatajer].[dbo].[TransactionEntry] as transactionsEntry
ON transactions.TransactionNumber=transactionsEntry.TransactionNumber
INNER JOIN [HQMatajer].[dbo].[Item] as items
ON transactionsEntry.ItemID=items.ID
INNER JOIN [HQMatajer].[dbo].[Supplier] as suppliers
ON items.SupplierID=suppliers.ID
where "+whereQuery; //I tried with txtQuery.text as well it doesn't work
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
//SqlDataReader rd = cmd.ExecuteReader();
//ASPxGridView1.Columns.Clear();
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
}
}
protected string getWhereQuery()
{
string query = txtQuery.Text;
return query;
}
By default (at first page load) you txtQuery.Text is empty, change your getWhereQuery to:
protected string getWhereQuery()
{
string query = txtQuery.Text;
if(string.IsNullOrEmpty(query))
query=" 1=1";
return query;
}
I am trying to hide this button if the query result is = to btn1.CommandArgument.
The query works, because I have tested it, but the whole solution is not work.
If I replace
myCommand.ExecuteScalar().ToString()
in the if statement to the query result, the button is hidden.
I have looked several times, but can't find any problems. Thank you.
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Button btn1 = (Button)e.Item.FindControl("addFollowerButton");
// request Query string
var querystring = Request.QueryString["ProjectId"];
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string select = "Select ProfileId from Project_Follower Where ProjectId = #ProjectId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
myCommand.ExecuteScalar();
if (myCommand.ExecuteScalar().ToString() == btn1.CommandArgument.ToString())
{
Button hdn = (Button)e.Item.FindControl("addFollowerButton");
btn1.Visible = false;
}
}
}
You need to execute the .ExecuteScalar() call only once! Grab the result (of type object) and then check to make sure it's not null and if it is, call .ToString() on it and compare to the other string you want to check against:
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
object result = myCommand.ExecuteScalar();
if (result != null && result.ToString().Equals(btn1.CommandArgument.ToString()))
{
Button hdn = (Button)e.Item.FindControl("addFollowerButton");
btn1.Visible = false;
}
}