Data is not updating into database [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to update the values of textboxes into my SQL Server database.
The code does not show any syntax error and redirects easily to the page I'm redirecting but still database is not updating the new data in it.
conn.Open();
string str_id = Session["userid"].ToString();
int id = Convert.ToInt32(str_id);
id = Int32.Parse(str_id);
string updatequery = "Update empdata set fname='" + updatename.Text + "',education='" + updateeducation.Text + "',position='" + updateposition.Text + "',email='" + updateemail.Text + "',address='" + updateaddress.Text + "',contact='" + updatecontact.Text + "',account='" + updateaccount.Text + "',postal='" + updatepostal.Text + "',password = '" + updatepwd.Text + "' Where id = '" +id.ToString()+ "'";
SqlCommand updateinfo = new SqlCommand(updatequery, conn);
updateinfo.ExecuteNonQuery();
updateinfo.Dispose();
updationmessage.Text="<p style='color:green;'>Information updated successfully</p>";

Firstly,switch to ParameterBinding, your code is prone to sql inection (and slower)
Secondly, check the return value of ExecuteNonQuery. If it is 0, then there was no change in the database, meaning no matching id has been found
Thirdly, check if you are within a transaction where you need to commit the transaction - otherwise you will not see anything in the database.

Related

I am struggling to link a SQL local server to my project [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am relatively new to c# and I am practicing adding databases to store my information. I cannot get the connection string to work for me. the code is :
SqlConnection con = new SqlConnection("Data Source = (LocalDB)/MSSQLLocalDB; AttachDbFilename='C:/Users/joeco_000/Documents/Visual Studio 2015/Projects/Telephone project/Telephone project/Database1.mdf';Integrated Security = True'");
I then have a button that will add the information to the database that is:
private void button2_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#" INSERT INTO Phon table (First,last,email,mobile,catagory) VALUES ('" + textBox2.Text + "' , '" + textBox3.Text + "' , '" + textBox4.Text + "' , '" + textBox5.Text + "','" + comboBox1.Text + "')");
cmd.ExecuteNonQuery();
con.Close();
I have taken this information from a tutorial that is 6 years old. Any help would be amazing.
You haven't associated the command with the connection before attempting to execute the query. One way to do this is:
SqlCommand cmd = new SqlCommand(sql, connection)
Another way is:
cmd.Connection = con;
The name Phon table is not a valid table name. If your table really has a space in its name you need to surround it with square braces
INSERT INTO [Phon table] (First,last,email.......
Note that this is in addition to associating your command with your connection as the other answer indicates.

Access 2013 syntax error on INSERT INTO statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following query in c# and don't have any idea why it shows me this error:
"syntax error on INSERT INTO statement".
I use Access 2013.
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO money (price,cardnum,checknum,dateTime,employeeid) values('" + TempPrice + "','" + TempCriditNum + "','" + TempCheckNum + "','" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "','" + id + "')";
command2.ExecuteNonQuery();
connection.Close();
A few things to check
dateTime is a reserved word. Try wrapping it in square brackets -
if the type of data you are dealing with is a Date\Time then you should be wrapping the input in # signs
if your data types are not strings, do not wrap them in quotes
as pointed out by Jia Jian, you should use parameterized queries
as pointed out by HansUp, Money is also a reserved word, so wrap it in square brackets
So the query ends up looking like :
command2.CommandText = "INSERT INTO [money] (price,cardnum,checknum,[dateTime],employeeid) values(" + TempPrice + "," + TempCriditNum + "," + TempCheckNum + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + id + ")";
Your SQL statement might be prone to SQL injection. Consider using parameterized queries by adding values via the OleDbCommand.Parameters property instead of concatenating it.
An example would be:
command2.CommandText = "INSERT INTO [money] (price, cardnum, checknum, [dateTime], employeeid) values(#tempPrice, #tempCreditNum, #tempCheckNum, #dateTime, #id)";
command2.Parameters.AddRange(new OleDbParameter[] {
new OleDbParameter("#tempPrice", TempPrice),
new OleDbParameter("#tempCreditNum", TempCriditNum),
new OleDbParameter("#tempCheckNum", TempCheckNum),
new OleDbParameter("#dateTime", dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString()),
new OleDbParameter("#id", id)
});
command2.ExecuteNonQuery();
This should also solve your syntax error.

c# simultaneous calls for sql db [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my C# project I have a method that ask if an object exists in the db and if not then creates it. Now, if two users asks the same question simultaneously they both get null so the flow will be to save to db which is impossible for two duplicates to do that, so will raise an sql exception.
How can I deal with this issue please?
here is my code:
var date = DateTime.UtcNow.Date;
var todayCelebPageView = _celebPageViewsRepo.GetAll().SingleOrDefault(d => d.iCelebId == celebId && d.dDate == date);
if (todayCelebPageView != null)
{
todayCelebPageView.iScore++;
_celebPageViewsRepo.Save();
}
else
{
todayCelebPageView = new MovliCelebPageView() {dDate = date, iCelebId = celebId, iScore = 1};
_celebPageViewsRepo.Add(todayCelebPageView);
_movliRepository.DbContext.Entry(todayCelebPageView).State = System.Data.EntityState.Added;
_celebPageViewsRepo.Save();
}
Theres no easy answer to this really, it's a common problem with a number of solutions.
Some options might be:
Catch the correct SQL exception, and re-try accordingly
Create a queue for those database calls, and handle them one at a time
Some implementation of locking, either in the database (perhaps by wrapping it in a transaction) or in the code itself.
Something else to consider is what should happen from a business point of view when two attempts are made to create a record at the same time.
Should the person who created the record last win? Should the first person win and the second receive an error? Or should you write the first record and update it again with the second?
The answer to this will depend entirely on the specifics of what you are trying to do in your application.
Move the logic of the check and create to the procedure level, then it will be handled with transaction isolation:
IF NOT EXISTS (SELECT 'non-empty' FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.TABLE_NAME') AND type in (N'U'))
CREATE TABLE dbo.TABLE_NAME
But you still have to wrap your method and handle exception according the Number property of SqlException:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
System Error Messages
Cause and Resolution of Database Engine Errors
You should wrap the test for existence and the insert in a transaction. In that way the second call to check for existence will block while the first is completing.

Error when execute query [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
HI here is code snippet of C#. I am trying to generate a summary of data and display in formview in asp.net. But having a issue with this code generating error that
'Incorrect syntax near 'K12'.'
please help me out.
try
{
SqlConnection conn = new SqlConnection("server=ARSLAN- LAPI\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=OTTS; " +
"connection timeout=30");
String query = "Select * FROM dbo.";
query = query + " " + "[" + session.SelectedItem.Text + "_" + dept.SelectedItem.Text + "]";
query = query + " " + "WHERE rollNo=" + "2K12-BSCS-37";
//SqlCommand cmd = new SqlCommand(query, conn);
//SqlDataReader reader;
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, conn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dataform.DataSource = table;
dataform.Visible = true;
}
catch (SqlException ex)
{
ErrorMessage.Text="Error ::"+ ex.Message;
}
The roll number string in your where clause needs to be delimited as a string. This line query = query + " " + "WHERE rollNo=" + "2K12-BSCS-37"; should be replaced with query += " " + "WHERE rollNo=" + "'2K12-BSCS-37'"; Note the single quotes.
Better still would be to use string format to build your query, something like this:
string.Format("SELECT * FROM dbo.[{0}_{1}] WHERE rollNo = '{2}'",
session.SelectedItem.Text,
dept.SelectedItem.Text,
"2K12-BSCS-37")
And even better still would be to avoid this dangerous query altogether, since it exposes your database to numerous possible attacks. I have honestly never let users build their own table name in this fashion, so I can't even say if the SQLClient parameters would work here, though I expect they will not. I agree with previous comments that much range checking, etc. will be required to make this viable.
In the end, hopefully this is an internal application that only a select few users will ever have access to.

asp.NET C# - Problems with ExecuteNonQuery() with Oracle Commands

I have this problem with a query I have, I am using Oracle Commands and Parameters. I have hundreds of other queries in my code, but just this one is failing to execute. It is a very simple update query and it works in SQL Navigator because I tried it.
Within the code, the execute non query method seems like it freezes and i get "Waiting for http:// localhost:8081/MaintainUserProfile.aspx" in my webpage.
I appreciate your help because I've wasted hours on it and I'm clueless at this stage.
Let me know if I should state more information.
The code below (Please note I work with oracle parameters, but in this case I am just using plain strings to debug the problem, the same happens with oracle parameters, it get stuck on execute non query):
string sqlQuery = #"UPDATE schema_name.table_name
SET
officer_name = '" + fullName +
"', channel_code = " + channelCode +
", male_female_ind = '" + maleFemale +
"', user_status_code = '" + userStatusCode +
"', identity_number = '" + idNumber +
"', extension_number = " + extensionNumber +
" WHERE user_profile_id = " + userProfileID;
OracleCommand oraCommand2 = new OracleCommand(sqlQuery, db);
oraCommand2.ExecuteNonQuery();
You can try with this code - Based on AddWithValue
oraCommand2.CommandText="UPDATE schema_name.table_name SET
officer_name = :fullName , channel_code = :channelCode,
male_female_ind = :male_female_ind, user_status_code = :user_status_code,
identity_number = :idNumber, extension_number = :extensionNumber
WHERE user_profile_id = :userProfileID";
oraCommand2.Parameters.AddWithValue(":fullName", fullName);
oraCommand2.Parameters.AddWithValue(":channelCode", channelCode);
oraCommand2.Parameters.AddWithValue(":male_female_ind", male_female_ind );
oraCommand2 .Parameters.AddWithValue(":user_status_code", user_status_code );
oraCommand2 .Parameters.AddWithValue(":identity_number", identity_number );
oraCommand2 .Parameters.AddWithValue(":extension_number", extension_number );
oraCommand2 .Parameters.AddWithValue(":user_profile_id", user_profile_id );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.oracleclient.oracleparametercollection.addwithvalue.aspx
Kenneth answered it in this Post, it may be due to an uncommitted operation in SQLDeveloper (or any other uncommitted pending database change).

Categories