How to make SQL query text parameter accept sentence containing an apostrophe - sql

How I am performing a SQL query to insert data into the database. Note that the field PlanDetails in the table dbo.Plans is a text field. However, when a user tries to input a sentence which contains an apostrophe (e.g. I'll go to sleep). via the HTML form . The database returns an error "Incorect syntax near ll), which refers to the apostrophe problem. In this case, how should I modify the code below to make it accept sentences with apostrophe? It is told that I can use parameterized queries. In this node js example, how can I do that?
CreatePlan : function (newPlan , UserID, DisplayName, Email, callback) {
var sql = require('mssql');
var config = require('./configuration/sqlconfig');
var conn = new sql.Connection(config);
var req = new sql.Request(conn);
conn.connect(function (err) {
if (err) {
console.log(err);
return;
}
console.log('Attempting to Insert new learning plan...');
req.query('INSERT INTO dbo.Plans (PlanTitle, PlanTopic, OwnerID, OwnerName, PlanDetails, TargetLearners, OwnerContact) VALUES ("' + newPlan.PlanTitle + '", "' + newPlan.PlanTopic + '", "' + UserID + '", "' + DisplayName + '", "' + newPlan.PlanDetails + '", "' + newPlan.TargetLearners + '", "' +Email+ '");', function (err) {
if (err) {
console.log(err);
} else {
console.log("Added one new learning plan");
console.log("The new plan title is " + newPlan.PlanTitle);
callback();
}
conn.close();
});
});
},

In SQL (and in many other languages), you have to escape special characters to avoid any ambiguity in the code. There is a lot of documentation about how to escape and which character are concerned all other internet.
Here is the wikipedia article about escape character: https://en.wikipedia.org/wiki/Escape_character
Here is a stackoverflow post that answer your question: How do I escape special characters in MySQL?
However I should warn you about SQL injection, the code you are using will not be safe and you should probably take a look at the good practice in this matter.

Related

MSSQL Returns Different result in SSMS and Node JS script

I have a SQL query to return customer's transaction header using customer's card_number. The SQL query will return a column called audit_number. The problem is the when i execute the SQL query using SSMS software, the query returns proper results, but when i execute the query on my Node JS script some of the audit_number are wrong.
The audit_number should be 14111990000015953 and 14111990000015952 but when i execute the query in my NODE JS script both audit_number become 14111990000015952.
Here is my sql query
SELECT
h.Log_trxdate AS trx_date,
CAST(h.log_audit AS varchar) AS audit_number,
h.currency_code
FROM log_header h
WHERE h.id_code = '10000010055919' --card_number
Here is my Node JS Script
var querySQL = " SELECT ";
querySQL = querySQL + " h.Log_trxdate AS trx_date, ";
querySQL = querySQL + " CAST(h.log_audit AS varchar) AS audit_number, ";
querySQL = querySQL + " FROM log_header h ";
querySQL = querySQL + " WHERE h.id_code = 10000010055919 ";
sql.connect(config, function (err) {
var req = new sql.Request();
req.query(querySQL, function (err, result) {
console.log(result);
});
});
You need to change your datatype number to varchar/text since in javascript if the number length is more than 16 digits then it will give you some random number.
So to get exact result you should change your Datatype from number to string.
For example if you check number
Number(1111111111111111)//16 digits
Result is 1111111111111111
But if you put Number(11111111111111111)//17 digits
then result will be 11111111111111112 something

Searching SQL for specific CHAR

I have a database table were a column holds multiple strings. They are holding License Plate numbers. If I search for 1 il get the first registration it finds with a one. I want to set it so that I must enter the full string and if I don't it should say not found. Here is my code. I'm sure its just the SQL command that needs altering for this.
public Car getCar(String searchLicense) {
Car foundCar = new Car();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
resultSet = statement
.executeQuery("select * from eflow.registration where cLicense like '%" + searchLicense + "%'");
while (resultSet.next()) {
foundCar = new Car(resultSet.getInt("cID"), resultSet.getString("cLicense"),
resultSet.getInt("cJourneys"), resultSet.getString("cUsername"),
resultSet.getString("cPassword").toString());
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return foundCar;
}
If you need the exact string, you will need to remove the '%' in the LIKE filter.
Your code should be:
cLicense like '" + searchLicense + "'
The '%' wildcard put before and after the parameter you have, enables you to search for any string containing the searchLicense value in the middle, without checks of what is before or after that string.
You should be using parameterized queries. Bobby Tables: A guide to preventing SQL injection
Then use = instead of like.
select * from eflow.registration where cLicense = #searchLicense

Inserting data through GUI into sql server

I'm able to execute sql statements by writing the sql codes (Insert etc) on Eclipse and it is being displayed into sql server correctly. Connection has been done. But what should I do when a user wants to add data through a GUI interface (text field) and the data need to get stored into the database automatically ??
my code in the ADD button, but i'm getting the Error: java.lang.NullPointerException ! Help please..
try {
String pid = ProductID.getText();
String sql = "insert into Products_tbl values (' " +pid + " ')";
// Running the sql query
rs = st.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Welcome");
}
else if (count > 1) {
JOptionPane.showMessageDialog(null,"Duplicate User Access Denied");
}
else {
JOptionPane.showMessageDialog(null, " User Not Found ");
}
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}
1- Using (' " +pid + " ')" is not safe because SQL injection may occur. Use SqlParameters instead. Please check:
https://www.w3schools.com/sql/sql_injection.asp
2- I am pretty sure something is wrong with the line: rs = st.executeQuery(sql);
Here, I bet the value of st is null. Make sure that your connection variable is defined and set correctly and you created the statement like below:
st = connection.createStatement();
You can also try executeupdate(query) instead of executequery(query) like:
int flag = st.executeUpdate(query);
Ref: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
3- Please use printStackTrace() method while printing the error in the catch blog, the error message would be more understandable.
System.out.println("Error: " + ex.printStackTrace());

ActionScript and SQLite parameters on Select using Like

I tried looking on google but without luck...
I have a SELECT SQLStatement and I want to use the LIKE operator but the parameters won't work and the query give me an error
public function getUsersList(username:String):SQLStatement
{
selectRecord= new SQLStatement();
selectRecord.sqlConnection = connection;
selectRecord.text =
"SELECT id_user, username,password,profile,leg_cliente " +
"FROM userlist " +
"WHERE username like '%:username%'";
selectRecord.parameters[":username"] = username;
return selectRecord;
}
The error I got is
':username' parameter name(s) found in parameters property but not in
the SQL specified.
I solved putting the wildcard % in the parameters instead of the statement...
selectRecord.text =
"SELECT id_user, username,password,profile,leg_cliente " +
"FROM userlist " +
"WHERE username like :username";
selectRecord.parameters[":username"] = "%"+ username+"%";
The starting problem was triggered because the query was like
selectRecord.text =
"SELECT id_user, username,password,profile,leg_cliente " +
"FROM userlist " +
"WHERE username like '%:username%'";
Putting the single quote in the statement won't let the statement to set the parameter, I suppose because the parameter key (in statement.text) is seen as a text and not a parameter itself...
This is a weird issue I've been stuck with for quite some time now. One solution I've used is like this:
var statementText:String="SELECT id_user, username,password,profile,leg_cliente " +
"FROM userlist " +
"WHERE username like '%:username%'";
var params:Dictionary=new Dictionary();
params[":username"] = username;
for(var key:Object in params) {
while(statementText.indexOf(key.toString()) >= 0) {
statementText= statementText.replace(key, params[key]);
}
}
selectRecord.text = statementText;

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 :-)