i have in asp.net a few textboxes and i wish to update my database with the values that they encapsulate .
The problem is that it doesn't work and although it doesn't work, the syntax seems correct and there are no errors present . Here is my linkbutton :
<asp:linkbutton id="clickOnSave" runat="server"
onclick="Save_Click" Text="Save Profile" />
and my update function
protected void Save_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "DataSource=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\alex\\Documents\\seeubook_db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
String commandString = "UPDATE users SET last_name='" + Text4.Text.Trim() + "' , first_name='" + Textbox1.Text.Trim() + "' , about_me='" + Textbox5.Text.Trim() + "' , where_i_live='" + Textbox2.Text.Trim() + "' , where_i_was_born='" + Textbox3.Text.Trim() + "' , work_place='" + Textbox4.Text.Trim() + "' WHERE email='" + Session["user"] + "'";
SqlCommand sqlCmd = new SqlCommand(commandString, con);
sqlCmd.ExecuteNonQuery();
con.Close();
}
I'm always a bit weary about the User Instance=true in a connection string..... at times, it tends to create a new MDF file "on the fly" and when you update that MDF, then your changes might be just "gone" one your app has completed running.... See MSDN docs on User Instances.
I would suggest that you:
attach your MDF file to SQL Server Express on your machine, using SQL Server Express Management Studio
then use a server-based approach to your SQL Server Express database rather than attaching a file...
In that case, your database connection string would then look something like:
server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;
And while you're at it, I would also recommend to:
wrap your SqlConnection and SqlCommand into using blocks to ensure proper disposal
open your connection as late as possible
use a parametrized query instead of concatenating together your SQL command - doing so is a wide open door for SQL injection attacks!
So your code would look something like this:
string connStr = "server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;";
string cmdStmt = "UPDATE dbo.Users SET last_name = #lastName, " +
"first_name = #firstName, about_me = #aboutMe, where_i_live = #whereILive, " +
"where_i_was_born = #whereIWasBorn, work_place = #workPlace " +
"WHERE email = #userEMail";
using(SqlConnection sqlCon = new SqlConnection(connStr))
using(SqlCommand sqlCmd = new SqlCommand(cmdStmt, sqlCon))
{
// define parameters
sqlCmd.Parameters.Add("#lastName", SqlDbType.VarChar, 50);
sqlCmd.Parameters["#lastName"].Value = Text4.Text.Trim();
// and so on for all the parameters
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
Debug! Look your LinkButton Click Event really go into Save_Click function. And then check 'sqlCmd.ExecuteNonQuery();' return result.
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
Related
I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler
I have a database name test.dbo. In the database it have two table named Equipment and backup. I want to move some data in the table Equipment to table backup and delete the data in the table Equipment. So, what is the query to use to do it?
I have use this query but it only move the data to table backup without deleting it in table Equipment. Moreover, if i use the query again , error show that the table name already exits.
protected void Button5_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=5CG50749V3\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * into test.dbo.[backup] from test.dbo.[Equipment] where (SerialNumber = '" + TextBox2.Text + "' or EquipmentID = '" + TextBox1.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
For this, instead of the SELECT * INTO, use a DELETE statement with an OUTPUT INTO clause.
Reference: https://msdn.microsoft.com/en-us/library/ms177564.aspx
Very frustrating one... I have tried many combinations of ', " and so on but my insert command just refreshing the page.
What am I doing wrong?
Simple two text fields form with button. Under button I have this:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString);
con.Open();
string cmdStr = "INSERT INTO specyfik(speNazwa, speIlosc) values ('" + speNazwa.Text + "', '" + speIlosc.Text + "')";
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
con.Close();
Zero errors while compiling and when testing, it seems like refreshed page. Nothing appears in db.
Don't you need to call insertCmd.ExecuteNonQuery() ?
...
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
int row_affected = insertCmd.ExecuteNonQuery();
...
You need to execute your SqlCommand:
insertCmd.ExecuteNonQuery();
Also, you should look into parameterizing that query:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Will you like to make more improvements in your code using stored Proc and improvemnet in your code behind file ? Take a look at this answer...
https://stackoverflow.com/a/9595501/1209450
I have a website with a login, from a database.
This is my code :
protected void SignIn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
con.Open();
string cmdStr = "select count(*) from Users";
cmdStr += "where Username='" + UsernameSignIn.Text + "'";
cmdStr+= "AND Password='"+PasswordSignIn.Text+"'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
int i = Convert.ToInt16(cmd.ExecuteScalar());
if (i == 0)
{
ErrorSignIn.Text = "Sorry, Wrong Username or Password";
}
else
{
Response.Redirect("HomeAfter.aspx");
}
}
for some reason, I run into an error :
Incorrect syntax near '-'
.
(for this line : int i = Convert.ToInt16(cmd.ExecuteScalar()); )
Thanks,
There is no spacing. Your query looks like this:
select count(*) from Userswhere Username='...'AND Password='...'
Add spaces, like so:
string cmdStr = "select count(*) from Users";
cmdStr += " where Username='" + UsernameSignIn.Text + "'";
cmdStr+= " AND Password='"+PasswordSignIn.Text+"'";
Aside from the fact that this is particularly crude as a form of authentication (you really ought to consider using the built-in ASP.NET Membership provider(s)) you should at a minimum be using parameterized SQL queries, rather than concatenating plain text to create your SQL statement. Also, I notice that your "login" arrangement simply does a response.redirect to the HomeAfter.aspx page without storing anything to be re-used that will indicate the user has already successfully logged in, such as a cookie or a sesssion variable.
Is there any particular reason for all this, or is it because you're just starting out and you need to study up a bit?
I am working on a project - online movie ticketing system....
In this when the user enters the number of seats he wants to book, he goes to payment page. On click of payment button, how can I decrement the number of seats entered by the user in SQL Server.
SqlConnection con;
SqlCommand cmd;
private void update()
{
string a, b;
int c;
con = new SqlConnection("server=.;uid=sa;pwd=mayank;database=movie");
a = Session["timings"].ToString();
b = Session["seats"].ToString();
c = Convert.ToInt32(b);
con.Open();
cmd = new SqlCommand("update bodyguard set silver_class = silver_class ' " + - c + " 'where timings = ' " + a + "' ", con);
cmd.ExecuteNonQuery();
con.Close();
}
With this code it is raising an exception....so please help me out.
Your SQL command is wrong, what you produce is this:
update bodyguard set silver_class = silver_class ' -[valueC] 'where timings = ' [valueA]'
You forgot a space before where for example, and I am not sure how the silver_class part is supposed to look, because it's not clear what you are trying to achieve there.
You had some single quotes around your integer value. try this
"update bodyguard set silver_class = (silver_class - " + c + ") where timings = '" + a + "'"
A little advice, you should use a try{}catch{} blocks to handle potential errors in your code. When you convert a number with Convert.toInt32(), you should try to catch a FormatException. And from con.open() to con.close you can try to catch the SQLException
Don't use concatenated strings to create your SQL statment, its really bad form. Do it this way:
cmd = new SqlCommand("update bodyguard set silver_class = silver_class - #c where timings = #a", con);
cmd.Parameters.AddWithValue("#c", c);
cmd.Parameters.AddWithValue( "#", a);
I recommend Parameterized Query instead of string concatenation which is vulnerable to SQL Injection. And I suggest that you should use Stored Procedure instead of Inline SQL.