SQL Server update in C# - sql

I try to UPDATE data in my SQL Server database and I get this error:
System.Data.SqlClient.SqlException
Incorrect syntax near 'de'
Unclosed quotation mark after the character string ')'
private void BtEnrMod_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\BD4X4;Initial Catalog=BD4X4;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Service SET Type = " + TxBxService.Text + ", Prix = " + TxBxPrix.Text + "WHERE Code = " + LbCodeAff.Text + "')", con);
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
MessageBox.Show("Service Modifié");
}
else
{
MessageBox.Show("Erreur");
}
this.Close();
con.Close();
}

Replace the one liner that declares your command with this code block:
SqlCommand cmd = new SqlCommand("UPDATE Service SET Type = #t, Prix = #p WHERE Code = #c", con);
cmd.Parameters.AddWithValue("#t", TxBxService.Text);
cmd.Parameters.AddWithValue("#p", TxBxPrix.Text);
cmd.Parameters.AddWithValue("#t", LbCodeAff.Text);
Always avoid writing an sql where you string concatenate in a value provided by the user in a text box; it's the number one security horror you can make with sql. Always use parameters to put values in, like you see here. For more info on this SQL injection hacking, see http://bobby-tables.com
If you ever fin yourself in a situation where you think you have to concatenate to make an sql, don't concatenate a value in; concatenate a parameter in and add the value into the parameters collection. Here's a hypothetical example:
var cmd = new SqlCommand("","connstr");
strSql = "SELECT * FROM table WHERE col IN (";
string[] vals = new[]{ "a", "b", "c" };
for(int x = 0; x<vals.Length; x++){
strSql += ("#p"+x+",");
cmd.Parameters.AddWithValue("#p"+x, vals[x]);
}
cmd.CommandText = strSql + ")";
This uses concatenation to make an sql of SELECT * FROM table WHERE col IN (#p0, #p1, #p2) and a nicely populated parameters collection
When you're done grokking that, read the link Larnu posted in the comments. There are good reasons to avoid using AddWithValue in various scenarios but it will always be preferable to concatenation of values. Never ditch the use of parameters "because I read a blog one time about how AddWithValue is bad" - form parameters using the new parameter constructor, or use AddWithValue shortcut, but never concat values
Or better still than all of this, use an ORM like Entity Framework, nHibernate or Dapper and leave most of this boring boilerplate low level SQL drudgery behind. These libraries do most of this wrangling for you; EF and nH even write th sql too, dapper you write it yourself but it takes care of everything else
Using a good ORM is like the difference between writing creating a UI manually line by line of position, font, anchor, event code for every button, label and text box versus using the windows forms designer; a world apart and there's no sense in taking hours to create manually what software can do more comprehensively, faster and safer for you in seconds

Related

How can i make a delete query with more that 1 condition?

I need to clear a row in the SQL database. Can I do it like this?:
string idprod = Request.QueryString["IDProduto"];
string size= Request.QueryString["Size"];
try
{
liga.Open();
SqlCommand comando = new SqlCommand();
comando.CommandText = "delete FROM dbo.M16_Tbl_Carrinho where ID_User=" +
Session["IDuser"] + " and ID_Produto="+idprod+" and Tamanho="+tamanho+"";
comando.Connection = liga;
Response.Redirect("Cart.aspx");
}
catch (Exception er)
{
Response.Write($"<script>alert({er.Message});</script>");
}
Short answer: Yes, you can do it that way, but there are good reasons to not do so.
Answer to the actual question: Yes, you can put as much as you want in the WHERE clause.
Advice against SQL injection: Never, ever concatenate values in a string in this way. Use prepared parameters. Example excerpt:
liga.Open();
SqlCommand comando = new SqlCommand();
comando.CommandText = "delete FROM dbo.M16_Tbl_Carrinho where ID_User=#iduser and ID_Produto=#idprod and Tamanho=#tamanho";
comando.Parameters.Add("#iduser").Value = iduser;
comando.Parameters.Add("#idprod").Value = idprod;
comando.Parameters.Add("#tamanho").Value = tamanho;
comando.Connection = liga;
I would suggest you to look at this example: https://www.c-sharpcorner.com/UploadFile/718fc8/save-delete-search-and-update-record-in-ado-net/
It has all CRUD operations example.
Also, do not use string concatenation. Instead use Sql parameter as suggested by #Ross.
Try to separate your presentation logic from data access logic. Your one method doing lots of things.

Problem reading foreign characters Winform Textbox from database

please help. in Visual Studio 2017 and SQL localDB - WinForm learns and makes a small application. Form (Textbox), where "name, surname, address, city, phone and email" is written in Czech language containing "ěščřžýáíé" ". Everything is stored in the database (nvarchar) in order. Everything OK.
In Form2 I have another form where Combobox calls a "surname" and it has to fill in the phone and e-mail automatically from the database. If the surname is without the character "ěščřžýáíé", everything will be displayed correctly. If it contains "ěščřžýáíé", only the last name will be displayed, but the phone and email will not be loaded into the TextBox.
The code sample (without ěščřžýáíé) works perfectly:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\newtest.mdf;Integrated Security=True");
string sql = "select * from test111 WHERE firmadat ='" + prijmeniComboBox.Text + "'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
string rollno = myreader.GetInt32(0).ToString();
string name = myreader.GetString(1);
string telephone = myreader.GetString(3);
string email = myreader.GetString(4);
textBox1.Text = rollno;
telefonTextBox.Text = telephone;
emailTextBox.Text = email;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Thank you for your help.
The problem is probably here:
string sql = "select * from test111 WHERE firmadat ='" + prijmeniComboBox.Text + "'; ";
Here you take your Unicode string and you concatenate it into a SQL string that is not a Unicode string. I would tell you how to get it working as you intended but this is a really really dangerous way to write SQLs. Someone at kids' toy maker VTech wrote SQLs this way and enabled a hacker to download millions of images of children taken by vtech devices. If one of my developers wrote SQL like this they would be subject to disciplinary action, possibly being fired.
I strongly recommend that you use parameterized SQLs; any number of internet resources will show you how, such as http://bobby-tables.com - it will also solve the problem of getting no results when searching using a search term that contains non-ASCII characters
Take a look at http://dapper-tutorial.net ; using dapper will not only take care of the parameterizing for you, but make your database life easier by reducing your code to just a couple of lines, something like:
using(SqlCommand x = new SqlCommand(conn)
{
var p = x.Query(
"select * from test111 WHERE firmadat = #a",
new { a = prijmeniComboBox.Text }
);
firstNameTextBox.Text = p.FirstName; //or what the column is called on db
...
}
You just write your sql, use #namedParameter placeholders and supply an anonymous object with properties named after the placeholders. Dapper does the rest. If you have a Person class in your project you can even get dapper to create it and populate it for you

Oracle Parameters in .net sql queries - ORA-00933: SQL command not properly ended

I am trying to do create a where clause to pass as a parameter to an Oracle command and it's proving to be more difficult than I thought. What I want to do is create a big where query based off user input from our application. That where query is to be the single parameter for the statement and will have multiple AND, OR conditions in it. This code here works however isn't exactly what I require:
string conStr = "User Id=testschema;Password=pass12341;Data Source=orapdex01";
Console.WriteLine("About to connect to Database with Connection String: " + conStr);
OracleConnection con = new OracleConnection(conStr);
con.Open();
Console.WriteLine("Connected to the Database..." + Environment.NewLine + "Press enter to continue");
Console.ReadLine();
// Assume the connection is correct because it works already without the parameterization
String block = "SELECT * FROM TEMP_VIEW WHERE NAME = :1";
// set command to create anonymous PL/SQL block
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = con;
// since execurting anonymous pl/sql blcok, setting the command type
// as text instead of stored procedure
cmd.CommandType = CommandType.Text;
// Setting Oracle Parameter
// Bind the parameter as OracleDBType.Varchar2
OracleParameter param = cmd.Parameters.Add("whereTxt", OracleDbType.Varchar2);
param.Direction = ParameterDirection.Input;
param.Value = "MY VALUE";
// Get returned values from select statement
OracleDataReader dr = cmd.ExecuteReader();
// Read the identifier for each result and display it
while (dr.Read())
{
Console.WriteLine(dr.GetValue(0));
}
Console.WriteLine("Selected successfully !");
Console.WriteLine("");
Console.WriteLine("***********************************************************");
Console.ReadKey();
If I change the lines below to be the type of result I want then I get an error "ORA-00933: SQL command not properly ended":
String block = "SELECT * FROM TEMP_VIEW :1";
...
...
param.Value = "WHERE NAME = 'MY VALUE' AND ID = 5929";
My question is how do I accomplish adding my big where query dynamically without causing this error?
Sadly there is no easy way to achieve this.
One thing you will need to understand with parameterised SQL in general is that bind parameters can only be used for values, such as strings, numbers or dates. You cannot put bits of SQL in them, such as column names or WHERE clauses.
Once the database has the SQL text, it will attempt to parse it and figure out whether it is valid, and it will do this without taking any look at the bind parameter values. It won't be able to execute the SQL without all of the values.
The SQL string SELECT * FROM TEMP_VIEW :1 can never be valid, as Oracle isn't expecting a value to immediately follow FROM TEMP_VIEW.
You will need to build up your SQL as a string and also build up the list of bind parameters at the same time. If you find that you need to add a condition on the column NAME, you add WHERE NAME = :1 to the SQL string and a parameter with name :1 and the value you wish to add. If you have a second condition to add, you append AND ID = :2 to the SQL string and a parameter with name :2.
Hopefully the following code should explain a little better:
// Initialise SQL string and parameter list.
String sql = "SELECT * FROM DUAL";
var oracleParams = new List<OracleParameter>();
// Build up SQL string and list of parameters.
// (There's only one in this somewhat simplistic example. If you have
// more than one parameter, it might be easier to start the query with
// "SELECT ... FROM some_table WHERE 1=1" and then append
// " AND some_column = :1" or similar. Don't forget to add spaces!)
sql += " WHERE DUMMY = :1";
oracleParams.Add(new OracleParameter(":1", OracleDbType.Varchar2, "X", ParameterDirection.Input));
using (var connection = new OracleConnection() { ConnectionString = "..."})
{
connection.Open();
// Create the command, setting the SQL text and the parameters.
var command = new OracleCommand(sql, connection);
command.Parameters.AddRange(oracleParams.ToArray());
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Do stuff with the data read...
}
}
}

string not accepting " 's " while writing to database

Hello everyone i am creating a settings page for another application using mvc4. In the settings page:
1.It contains two text areas wherein the user can type anything.
2.After typing if the user clicks submit button, the text he has written is saved in a sql database.
3.The main application will read that data from the database and display it.
Here are my respective codes:
Model:
public string PartnerInfo1 { get; set; }
public string PartnerInfo2 { get; set; }
Controller:
[HttpPost]
public ActionResult Index(AddDetailModel model)
{
pinfo1 = model.PartnerInfo1;
pinfo2 = model.PartnerInfo2;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sample"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1='" + pinfo1 + "',PartnerInfo2='" + pinfo2 + "' where [PartnerID]='cs'", con);
cmd.ExecuteNonQuery();
return RedirectToAction("Index");
}
and in the view:
#Html.TextAreaFor(m => m.PartnerInfo1)
#Html.TextAreaFor(m => m.PartnerInfo2)
in the database, the corresponding table contains two columns PartnerInfo1,PartnerInfo2 and their datatype is nvarchar(max).
My problem is when i type apostrophe in text area it gives me error.For example if i type "world's" it gives error on clicking submit button.
This is the error:
Incorrect syntax near 's'.
Unclosed quotation mark after the character string ''.
Please suggest what i can do to avoid this.Any help would be appreciated.
Never do that - it's unsafe and allow to make sql injection:
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1='" + pinfo1 + "',PartnerInfo2='" + pinfo2 + "' where [PartnerID]='cs'", con);
Instead of that use the following parameters syntax:
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1=#pinfo1, PartnerInfo2=#pinfo2 where [PartnerID]='cs'", con);
cmd.Parameters.AddWithValue("#pinfo1", pinfo1);
cmd.Parameters.AddWithValue("#pinfo2", pinfo2);
Your method expose your query to sql injection attacks. You are much better using a parameterised query which will sort out your ' issue as well.
string connString = ConfigurationManager.ConnectionStrings["Sample"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("Update dbo.Partner_Design " +
"Set PartnerInfo1=#pinfo1, " +
"PartnerInfo2=#pinfo2 " +
"Where [PartnerID]=#partnerId", con);
cmd.Parameters.AddWithValue("#pinfo1", model.PartnerInfo1);
cmd.Parameters.AddWithValue("#pinfo2", model.PartnerInfo2);
cmd.Parameters.AddWithValue("#partnerId", "cs");
con.Open();
cmd.ExecuteNonQuery();
}
You can escape the single quote by prefixing it with another single quote, which would require doing a replace on your string before you add it to the query i.e.:
pinfo1 = pinfo1.Replace("'", "''");
pinfo2 = pinfo2.Replace("'", "''");
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1='" + pinfo1 + "',PartnerInfo2='" + pinfo2 + "' where [PartnerID]='cs'", con);
I would however strongly advise against this and take the advice of the other responses that instead use parameterised SQL which is much more secure. Note also that this solution will only solve your single quotes problem, and will still cause issues with other special characters that need escaping individually. As such whilst this should answer your question, the solutions proposed by Sławomir Rosiek and Kaf are much more comprehensive, much safer, and are best practice.
The method you are using leaves you open to SQL injection attacks.

Is it possible to run native sql with entity framework?

I am trying to search an XML field within a table, This is not supported with EF.
Without using pure Ado.net is possible to have native SQL support with EF?
For .NET Framework version 4 and above: use ObjectContext.ExecuteStoreCommand() if your query returns no results, and use ObjectContext.ExecuteStoreQuery if your query returns results.
For previous .NET Framework versions, here's a sample illustrating what to do. Replace ExecuteNonQuery() as needed if your query returns results.
static void ExecuteSql(ObjectContext c, string sql)
{
var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
DbConnection conn = entityConnection.StoreConnection;
ConnectionState initialState = conn.State;
try
{
if (initialState != ConnectionState.Open)
conn.Open(); // open connection if not already open
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close(); // only close connection if not initially open
}
}
Using Entity Framework 5.0 you can use ExecuteSqlCommand to execute multi-line/multi-command pure SQL statements. This way you won't need to provide any backing object to store the returned value since the method returns an int (the result returned by the database after executing the command).
Sample:
context.Database.ExecuteSqlCommand(#
"-- Script Date: 10/1/2012 3:34 PM - Generated by ExportSqlCe version 3.5.2.18
SET IDENTITY_INSERT [Students] ON;
INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (12,N'First Name',N'SecondName',{ts '1988-03-02 00:00:00.000'},N'RUA 19 A, 60',N'MORADA DO VALE',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3346-7125',NULL,NULL,{ts '2011-06-04 21:25:26.000'},2,1);
INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (13,N'FirstName',N'LastName',{ts '1976-04-12 00:00:00.000'},N'RUA 201, 2231',N'RECANTO FELIZ',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3341-6892',NULL,NULL,{ts '2011-06-04 21:38:38.000'},2,1);
");
For more on this, take a look here: Entity Framework Code First: Executing SQL files on database creation
For Entity Framework 5 use context.Database.SqlQuery.
And for Entity Framework 4 use context.ExecuteStoreQuery
the following code:
public string BuyerSequenceNumberMax(int buyerId)
{
string sequenceMaxQuery = "SELECT TOP(1) btitosal.BuyerSequenceNumber FROM BuyerTakenItemToSale btitosal " +
"WHERE btitosal.BuyerID = " + buyerId +
"ORDER BY CONVERT(INT,SUBSTRING(btitosal.BuyerSequenceNumber,7, LEN(btitosal.BuyerSequenceNumber))) DESC";
var sequenceQueryResult = context.Database.SqlQuery<string>(sequenceMaxQuery).FirstOrDefault();
string buyerSequenceNumber = string.Empty;
if (sequenceQueryResult != null)
{
buyerSequenceNumber = sequenceQueryResult.ToString();
}
return buyerSequenceNumber;
}
To return a List use the following code:
public List<PanelSerialList> PanelSerialByLocationAndStock(string locationCode, byte storeLocation, string itemCategory, string itemCapacity, byte agreementType, string packageCode)
{
string panelSerialByLocationAndStockQuery = "SELECT isws.ItemSerialNo, im.ItemModel " +
"FROM Inv_ItemMaster im " +
"INNER JOIN " +
"Inv_ItemStockWithSerialNoByLocation isws " +
" ON im.ItemCode = isws.ItemCode " +
" WHERE isws.LocationCode = '" + locationCode + "' AND " +
" isws.StoreLocation = " + storeLocation + " AND " +
" isws.IsAvailableInStore = 1 AND " +
" im.ItemCapacity = '" + itemCapacity + "' AND " +
" isws.ItemSerialNo NOT IN ( " +
" Select sp.PanelSerialNo From Special_SpecialPackagePriceForResale sp " +
" Where sp.PackageCode = '" + packageCode + "' )";
return context.Database.SqlQuery<PanelSerialList>(panelSerialByLocationAndStockQuery).ToList();
}
Keep it simple
using (var context = new MyDBEntities())
{
var m = context.ExecuteStoreQuery<MyDataObject>("Select * from Person", string.Empty);
//Do anything you wonna do with
MessageBox.Show(m.Count().ToString());
}
public class RaptorRepository<T>
where T : class
{
public RaptorRepository()
: this(new RaptorCoreEntities())
{
}
public RaptorRepository(ObjectContext repositoryContext)
{
_repositoryContext = repositoryContext ?? new RaptorCoreEntities();
_objectSet = repositoryContext.CreateObjectSet<T>();
}
private ObjectContext _repositoryContext;
private ObjectSet<T> _objectSet;
public ObjectSet<T> ObjectSet
{
get
{
return _objectSet;
}
}
public void DeleteAll()
{
_repositoryContext
.ExecuteStoreCommand("DELETE " + _objectSet.EntitySet.ElementType.Name);
}
}
So what do we say about all this in 2017? 80k consultations suggests that running a SQL request in EF is something a lot of folk want to do. But why? For what benefit?
Justin, a guru with 20 times my reputation, in the accepted answer gives us a static method that looks line for line like the equivalent ADO code. Be sure to copy it well because there are a few subtleties to not get wrong. And you're obliged to concatenate your query with your runtime parameters since there's no provision for proper parameters. So all users of this method will be constructing their SQL with string methods (fragile, untestable, sql injection), and none of them will be unit testing.
The other answers have the same faults, only moreso. SQL buried in double quotes. SQL injection opportunities liberally scattered around. Esteemed peers, this is absolutely savage behaviour. If this was C# being generated, there would be a flame war. We don't even accept generating HTML this way, but somehow its OK for SQL. I know that query parameters were not the subject of the question, but we copy and reuse what we see, and the answers here are both models and testaments to what folk are doing.
Has EF melted our brains? EF doesn't want you to use SQL, so why use EF to do SQL.
Wanting to use SQL to talk to a relational DB is a healthy, normal impulse in adults. QueryFirst shows how this could be done intelligently, your sql in .sql file, validated as you type, with intellisense for tables and columns. The C# wrapper is generated by the tool, so your queries become discoverable in code, with intellisense for your inputs and results. End to end strong typing, without ever having to worry about a type. No need to ever remember a column name, or its index. And there are numerous other benefits... The temptation to concatenate is removed. The possibility of mishandling your connections also. All your queries and the code that accesses them are continuously integration-tested against your dev DB. Schema changes in your DB pop up as compile errors in your app. We even generate a self test method in the wrapper, so you can test new versions of your app against existing production databases, rather than waiting for the phone to ring. Anyone still need convincing?
Disclaimer: I wrote QueryFirst :-)