How to fix my update statement in C# API? - c#

I wrote this below code and I am not able to update fields.
There is no error message, however my data is not getting updated.
public void UpdateTeacher(int id, [FromBody]Teacher TeacherInfo)
{
MySqlConnection Conn = Teachers.AccessDatabase();
//Open the connection between the web server and database.
Conn.Open();
//Establish a new command(query) for our database.
MySqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "update teachers set teacherfname=TeacherFname, teacherlname=TeacherLname, employeenumber=EmployeeNumber,salary=Salary where teacherid=TeacherId";
cmd.Parameters.AddWithValue("#TeacherFname", TeacherInfo.TeacherFname);
cmd.Parameters.AddWithValue("#TeacherLname", TeacherInfo.TeacherLname);
cmd.Parameters.AddWithValue("#EmployeeNumber", TeacherInfo.EmployeeNumber);
cmd.Parameters.AddWithValue("#Salary", TeacherInfo.Salary);
cmd.Parameters.AddWithValue("#TeacherId", id);
cmd.Prepare();
cmd.ExecuteNonQuery();
Conn.Close();
}
I tried insert and delete, they are working, however update query is not working.

If you look at how you are adding your parameters, you stated that the parameter name starts with an '#' symbol.
cmd.Parameters.AddWithValue("#TeacherFname", TeacherInfo.TeacherFname);
...
But if you look at your SQL text, you have not used the '#' symbol, so you need to add this at the front of all your parameter names.
cmd.CommandText = "update teachers set teacherfname=#TeacherFname, teacherlname=#TeacherLname, employeenumber=#EmployeeNumber,salary=#Salary where teacherid=#TeacherId";
As also stated in the comments, using AddWithValue is generally considered bad. See this for more details:
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Related

Updating Values with C# in SQL Table

I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx

Unable to insert data to database in asp.net C#

I'm new in C# programming, so I'll appreciate if anyone can help me. I know there are similar question but I still can't find the solution for my problem. I'm developing a mock system, where when user bought the product, the system will store all the transaction details. the problem is, I cannot insert the data into the database. Here's the code:
using (SqlConnection conn = new SqlConnection
(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string QueryA = "#Insert into TransDetails(AccountNumber,Amount,Provider"
+ ",Mobile Number,TransNum,TransDate, Status) "
+ " Values (#AccountNumber,#Amount,#Provider,#Mobile Number,"
+ "#TransNum,#TransDate,#Status";
using (SqlCommand cmd = new SqlCommand("InsertRecord", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = QueryA;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
}
and the stores procedures are as follows:
ALTER PROCEDURE InsertRecord1
#AccountNumber int,
#Amount nchar(10),
#Provider nchar(10),
#MobileNumber int,
#TransNum nchar(10),
#TransDate date,
#Status nchar(10)
AS
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,TransNum,TransDate,Status)
Values (#AccountNumber,#Amount,#Provider,#MobileNumber,#TransNum,#TransDate,#Status)
return
Really appreciate any help.
P/S: i dont know why the beginning of the stored procedures started with "alter".
I may be reading it wrong, but it looks like your stored procedure is not used at all. Try commenting out "cmd.CommandText = QueryA;" and substitute "cmd.CommandText = "InsertRecord1";" and change CommandType to StoredProcedure.
QueryA, by the way, is missing a paren at the end. However, the whole thing is unnecessary since you have a stored procedure that does the same thing and it's almost always preferable to use a stored procedure rather than embedded DML.
You must escape Mobile Number while brackets
Insert into TransDetails(AccountNumber,Amount,Provider,[Mobile Number],...
and remove the space in your parameter
...,#MobileNumber,#TransNum,#TransDate,#Status
and change the paramname in your command parameter
cmd.Parameters.AddWithValue("#MobileNumber", lblNumber.Text);
but seeing your stored procedure, the column Mobile Number has no space between it. Is it a typo error in your query on QueryA? If it is, then remove the space on it (also on parameter name)
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,...
or
change your CommandType.Text to CommandType.StoredProcedure and remove this line,
cmd.CommandText = QueryA;
You're using the wrong overload of the SqlCommand constructor. According to MSDN:
new SqlCommand(string, SqlConnection) Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
What you need to do is either set your CommandType for the sql command to CommandType.StoredProcedure and not use QueryA, or initialize the sql command with QueryA and not make use of your stored procedure.
As you can see there is # at the start of your SQL Statement.
Also you are not really using the Store Procedure.
You can Try this:
using (SqlConnection conn = new SqlConnection (ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("InsertRecord1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
Tho I don't use SQL Commands, Adapters...etc. to access the data from the SQL Database. I prefer Microsoft Data Access ApplicationBlocks which is easy-to-use library provided by Microsoft to access data from SQL Server.
Download
You can download it here http://download.microsoft.com/download/VisualStudioNET/daabref/RTM/NT5/EN-US/DataAccessApplicationBlock.msi
Introduction
https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx

Unable to insert data into SQL Database using C#

I'm writing a method to insert a Student into a local SQL database that contains a table with information about Students:
public void AddStudent(string name, string teachName, string pass)
{
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\Logo.sdf";
SqlCeConnection connection = new SqlCeConnection("Data Source=" + dbfile + "; Password = 'dbpass2011!'");
connection.Open();
SqlCeTransaction transaction = connection.BeginTransaction();
SqlCeCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO Students VALUES ('#name', '#id', '#pass', '#tname')";
command.Parameters.Add("#name", name);
command.Parameters.Add("#id", this.ID);
command.Parameters.Add("#pass", MD5Encrypt.MD5(pass));
command.Parameters.Add("#tname", teachName);
command.Prepare();
command.ExecuteNonQuery();
transaction.Commit();
connection.Dispose();
connection.Close();
}
Whenever I use this, it never inserts the data to the table when I look at the contents of the Students table in the database. Originally I had this return an int so I could see how many rows it affected, which it always returned 1, so I know it's working.
I've looked for answers to this, and the answer to similar questions was that the person asking was looking at the wrong .sdf file. I've made sure that I'm looking at the right file.
Any feedback would be much appreciated!
command.CommandText = "INSERT INTO Students VALUES ('#name', '#id', '#pass', '#tname')";
You should remove the extra single quotes - this should be:
command.CommandText = "INSERT INTO Students VALUES (#name, #id, #pass, #tname)";
Also I am not sure why you open a transaction for a single insert - that is also not needed.
You don't need to put single quote to parametrized query, in case of parametrized query the whole data will be parsed as required,
command.CommandText = "INSERT INTO Students VALUES (#name, #id, #pass, #tname)";
Also, its better to set parameter type, size and value explicitly as below:
SqlCeParameter param = new SqlCeParameter("#name", SqlDbType.NVarChar, 100);
param.Value = name; // name is a variable that contain the data of name field
//param.Value = 'Jhon Smith'; //Directly value also can be used
Hope this would be helpful, thanks for your time.
There is most likely an exception being raised in your code; you need to add a try/catch handler and/or debug the application to figure out exactly what is happening.
However, there are at least two issues with your code:
The prepare statement requires the data types of the parameters. From the MSDN documentation:
Before you call Prepare, specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable-length data type, you must set the Size property to the maximum size needed. Prepare returns an error if these conditions are not met.
You need to close the connection before disposing it (this won't affect the insert, however).

How to save HTML content in database

I have text area on my page. In that area I have to add some HTML code and save it to database. And it works for simple html, but when I select some text from "wikipedia" for example and paste it and try to save when SQL Query need to be executed I got exception with following error:
Incorrect syntax near 's'.
The identifier that starts with '. Interestingly, old maps show the name as <em>Krakow</em>.</p>
<p>Kragujevac experienced a lot of historical turbulence, ' is too long. Maximum length is 128.
The identifier that starts with '>Paleolithic</a> era. Kragujevac was first mentioned in the medieval period as related to the public square built in a sett' is too long. Maximum length is 128.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
Unclosed quotation mark after the character string '>Belgrade Pashaluk</a>.</p>'
I am using asp mvc and razor engine. I don't know maybe I need to encome html somehow. I have also added this for ArticleText property:
[AllowHtml]
public string ArticleText { get; set; }
This is code for saving to database:
string sql = #"insert into tbl_articles
(Text) values
("'" + article.ArticleText"'"+")";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
Wow, NO, NO, NO. Your code is vulnerable to SQL injection and very bad stuff will happen if you don't use parametrized queries. So use parametrized queries.
using (var conn = new SqlConnection("some conn string"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "insert into tbl_articles (Text) values (#Text)";
cmd.Parameters.AddWithValue("#Text", article.ArticleText);
cmd.ExecuteNonQuery();
}
Everytime you use the + operator to concatenate strings when building a SQL query you are doing something extremely dangerous and wrong.
Try to save this way:
string sqlQuery = "INSERT INTO tbl_articles (Text) VALUES (#text)";
SqlCommand cmd = new SqlCommand(sqlQuery, db.Connection);
cmd.Parameters.Add("#text", article.ArticleText);
cmd.ExecuteNonQuery();
Try:
string sql = #"insert into tbl_articles
(Text) values
(#articleText)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#articleText",
Server.HtmlEncode(article.articleText));
cmd.ExecuteNonQuery();
This is a classic example of opening your system to a Sql injection attack.
You need to escape the ' character because if the Html contains the ' character, it will break the SQL Statement when it is executed.
EDIT: Use Darins solution to solve the problem.
this should be parameterized:
public void foo(string connectionString, string textToSave)
{
var cmdString = "insert into tbl_articles (text) values (#text)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand comm = new SqlCommand(cmdString, conn))
{
comm.Parameters.Add("#text", SqlDbType.VarChar, -1).Value = textToSave;
comm.ExecuteNonQuery();
}
}
}
(this is the gereral idea, it's not completely functional as written.)

System.Data.OleDb.OleDbException: Number of query values and destination fields are not the same

I received some help which I much appreciate to insert info into a database using paramaters as it is better practice I believe to do this.
I do however get the following error 'Number of query values and destination fields are not the same'. Not sure as to why it is happening.
The code seems perfectly fine and the database.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES(#title, #rating. #review, #ISBN, #userName)";
//adding my parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#title", title),
new OleDbParameter("#rating", rating),
new OleDbParameter("#review", review),
new OleDbParameter("#ISBN", ISBN),
new OleDbParameter("#userName", userName),
});
cmd.ExecuteNonQuery();
conn.Close();
}
Advice perhaps as to why this error exist?
Kind regards
Arian
There is a . (period) instead of a , (comma) in your INSERT statement after the #rating parameter.
Change the . to comma.
INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])
VALUES(#title, #rating, #review, #ISBN, #userName)
I think this may be as simple as that a period has been put in place of a comma where the parameters are specified:
#rating. #review
should be:
#rating, #review

Categories

Resources