I'm trying to update a database in JavaFX using JDBC and Textfields ,
The first textfields, but I keep getting SQL syntax errors.
It's a simple update syntax , but I have to use the textfield.getText() in order to fill up the data.
I tried this as the query I'll execute:
UPDATE intervention
set "+update_textfield2.getText()+" = "+update_textfield3.getText()+"
WHERE ( Numdemande ="+update_textfield.getText()+"
To explain the code above : set the database field the user entered (update_textfield2) as the value the user entered (update_textfield3) where the "Numdemande" number is x (update_textfield)
While your code is unsafe, as explained in the comments, I'll answer on the assumption that your class has not yet covered SQL injection attacks.
As for your SQL statement itself, there are several problems.
First of all, you are using double quotes " instead of single quotes '. It is unclear which dialect of SQL you are using, but most, if not all, require single quotes when passing through Strings like this.
Secondly, you are wrapping your calls to the textField.getText()
methods in quotes, meaning you're telling SQL to use that text
literally.
You have not added a closing parentheses ()) at the end of your WHERE clause. The parentheses in this case, however, are not necessary.
In essence, you're trying to pass the following statement to SQL:
UPDATE intervention
set +update_textfield2.getText()+ = '+update_textfield3.getText()+'
WHERE ( Numdemande = '+update_textfield.getText()+'
Unless you have a field called +update_textfield2.getText()+ in your table, this statement will fail.
The following String would produce the correct statement:
String statement = "UPDATE intervention " +
"SET " + update_textfield2.getText() + " = " + update_textfield3.getText() +
"WHERE Numdemande = " + update_textfield.getText() + ";";
Side Note: Please learn the Java Naming Conventions and stick to them. In your code, you've used Snake Case when naming your TextField, but should be using Camel Case instead. An appropriate name for your TextField might be something like this instead: updateTextField1
I am using Visual Foxpro 9 with SQL Server as back-end. I am executing this query to update an existing column value with a unicode text:
UPDATE <table> SET fname = "N('" + hexchr + "')"
The problem is Foxpro is storing string as:
N(0945;0987;)
whereas when the same command is run via SQL Server management studio, the string is stored as actual devnagari font.
How to make Foxpro execute the above query with the N?
I've never tried working with Unicode and feeding SQL-Server... However, with respect to helping prevent SQL-Injection, in VFP, when using SQL-Passthrough (SQLConnect(), SQLExec(), etc), If you write your query with "?" place-holder, it will look at the VARIABLE from within VFP... such as
myField = 0x123 && or whatever hex value... VFP leading with 0x implies hex
myKey = "whatever"
cSQLCmd = "update SomeTable set Field1 = ?myField where SomeKey = ?myKey"
nSQLHandle = sqlconnect( YourConnectionStringInfo )
SQLExec( nSQLHandle, cSQLCmd )
sqldisconnect( nSQLHandle )
VFP will handle the ? parameters for you by their respective found variable names that are available. Now, all that being said, VFP was only based on 32 bit, and don't believe it recognizes "unicode" values. What you may need to do is create a stored procedure in SQL that accepts two hex value (or whatever), and call that and pass it in as so required.
I have a insertion statement that will insert the values from text boxes. It working fine now i want to check the text box must not be empty by using sql query.
My insertion statement is like this:
INSERT INTO guestpasstypes(guestPasstype_Name)values('" + tbPassType.Text + "')"
I also agree that you should avoid calling that SQL, due to the potential for injection attacks, but if for some reason, your really need to do it, then this should do the trick:
"INSERT INTO guestpasstypes(guestPasstype_Name)
select '" + tbPassType.Text + "' from dual where '" + tbPassType.Text + "' <> '';"
Use whatever language that you using to get the text from the text box to see if it's empty or null. Most languages have these checks. (ex: php; isempty()) Also, if you don't want spaces, use trim as well.
Make guestPasstype_Name to be NOT NULL and ensure that MySQL runs in SQL conformance mode. Following might work:
INSERT INTO guestpasstypes(guestPasstype_Name)values(
IF('" + tbPassType.Text + "'='', NULL,'" + tbPassType.Text+"')"
I can see two solutions
Check 'tbPassType.Text' before you generate sql query (recommended)
Create check constraint in the 'guestpasstypes' table like this:
ALTER TABLE dbo.guestpasstypes ADD CONSTRAINT
CK_guestPasstype_Name CHECK ((LEN(guestPasstype_Name])>(0)))
(the given example is for MSSQL but I hope MySQL has constrainrs too)
When should i use mysql_real_escape_string?
Is it only when i'm inserting rows into a database? Or only when i have user input?
Thanks
You should use mysql_real_escape_string() whenever you're building a query that will be run against the database. Any user input that is being used to build a database query should be run through this function. This will prevent sql injection attacks.
User inputs are your big area of concern when it comes to this.
You should use mysql_real_escape_string when you are inserting the value of a string into an SQL statement, and you are using the MySQL API.
$sql = "SELECT * FROM student WHERE foo = '" . $foo . "'";
Should be:
$sql = "SELECT * FROM student WHERE foo = '" .
mysql_real_escape_string($foo) . "'";
However you should also consider using PDO with prepared statements and bind parameters instead of mysql_real_escape_string. This reduces the risk of errors.
always, apart from integers, there you use intval()
It will simply filter all special character which included in form data to prevent from SQL injection(SQL injection is a hacker tool for hacking website through some queries with form data}
I just asked an SQL related question, and the first answer was: "This is a situation where dynamic SQL is the way to go."
As I had never heard of dynamic SQL before, I immediately searched this site and the web for what it was. Wikipedia has no article with this title. The first Google results all point to user forums where people ask more or less related questions.
However, I didn't find a clear definition of what a 'dynamic SQL' is. Is it something vendor specific? I work with MySQL and I didn't find a reference in the MySQL handbook (only questions, mostly unanswered, in the MySQL user forums).
On the other hand, I found many references to stored procedures. I have a slightly better grasp of what stored procedures are, although I have never used any. How are the two concepts related? Are they the same thing or does one uses the other?
Basically, what is needed is a simple introduction to dynamic SQL for someone who is new to the concept.
P.S.: If you feel like it, you may have a go at answering my previous question that prompted this one: SQL: How can we make a table1 JOIN table2 ON a table given in a field in table1?
Dynamic SQL is merely where the query has been built on the fly - with some vendors, you can build up the text of the dynamic query within one stored procedure, and then execute the generated SQL. In other cases, the term merely refers to a decision made by code on the client (this is at least vendor neutral)
Other answers have defined what dynamic SQL is, but I didn't see any other answers that attempted to describe why we sometimes need to use it. (My experience is SQL Server, but I think other products are generally similar in this respect.)
Dynamic SQL is useful when you are replacing parts of a query that can't be replaced using other methods.
For example, every time you call a query like:
SELECT OrderID, OrderDate, TotalPrice FROM Orders WHERE CustomerID = ??
you will be passing in a different value for CustomerID. This is the simplest case, and one that can by solved using a parameterized query, or a stored procedure that accepts a parameter, etc.
Generally speaking, dynamic SQL should be avoided in favor of parameterized queries, for performance and security reasons. (Although the performance difference probably varies quite a bit between vendors, and perhaps even between product versions, or even server configuration).
Other queries are possible to do using parameters, but might be simpler as dynamic SQL:
SELECT OrderID, OrderDate, TotalPrice FROM Orders
WHERE CustomerID IN (??,??,??)
If you always had 3 values, this is as easy as the first one. But what if this is a variable-length list? Its possible to do with parameters, but can be very difficult. How about:
SELECT OrderID, OrderDate, TotalPrice FROM Orders WHERE CustomerID = ??
ORDER BY ??
This can't be substituted directly, you can do it with a huge complicated CASE statement in the ORDER BY explicitly listing all possible fields, which may or may not be practical, depending on the number of fields available to sort by.
Finally, some queries simply CAN'T be done using any other method.
Let's say you have a bunch of Orders tables (not saying this is great design), but you might find yourself hoping you can do something like:
SELECT OrderID, OrderDate, TotalPrice FROM ?? WHERE CustomerID = ??
This can't be done using any other methods. In my environment, I frequently encounter queries like:
SELECT (programatically built list of fields)
FROM table1 INNER JOIN table2
(Optional INNER JOIN to table3)
WHERE (condition1)
AND (long list of other optional WHERE clauses)
Again, not saying that this is necessarily great design, but dynamic SQL is pretty much required for these types of queries.
Hope this helps.
Dynamic SQL is simply a SQL statement that is composed on the fly before being executed. For example, the following C# (using a parameterized query):
var command = new SqlCommand("select * from myTable where id = #someId");
command.Parameters.Add(new SqlParameter("#someId", idValue));
Could be re-written using dynamic sql as:
var command = new SqlCommand("select * from myTable where id = " + idValue);
Keep in mind, though, that Dynamic SQL is dangerous since it readily allows for SQL Injection attacks.
Dynamic SQL is a SQL built from strings at runtime. It is useful to dynamically set filters or other stuff.
An example:
declare #sql_clause varchar(1000)
declare #sql varchar(5000)
set #sql_clause = ' and '
set #sql = ' insert into #tmp
select
*
from Table
where propA = 1 '
if #param1 <> ''
begin
set #sql = #sql + #sql_clause + ' prop1 in (' + #param1 + ')'
end
if #param2 <> ''
begin
set #sql = #sql + #sql_clause + ' prop2 in (' + #param2 + ')'
end
exec(#sql)
It is exactly what Rowland mentioned. To elaborate on that a bit, take the following SQL:
Select * from table1 where id = 1
I am not sure which language you are using to connect to the database, but if I were to use C#, an example of a dynamic SQL query would be something like this:
string sqlCmd = "Select * from table1 where id = " + userid;
You want to avoid using dynamic SQL, because it becomes a bit cumbersome to keep integrity of the code if the query get too big. Also, very important, dynamic SQL is susceptible to SQL injection attacks.
A better way of writing the above statement would be to use parameters, if you are using SQL Server.
Rowland is correct, and as an addendum, unless you're properly using parameters (versus just concatonating parameter values inline from provided text, etc.) it can also be a security risk. It's also a bear to debug, etc.
Lastly, whenever you use dynamic SQL unwisely, things are unleashed and children are eaten.
To most databases, every SQL query is "dynamic" meaning that it is a program that is interpreted by the query optimiser given the input SQL string and possibly the parameter bindings ("bind variables").
Static SQL
However, most of the time, that SQL string is not constructed dynamically but statically, either in procedural languages like PL/SQL:
FOR rec IN (SELECT * FROM foo WHERE x = 1) LOOP
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "static SQL"
..
END LOOP;
Or in client / host languages like Java, using JDBC:
try (ResultSet rs = stmt.executeQuery("SELECT * FROM foo WHERE x = 1")) {
// "static SQL" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
..
}
In both cases, the SQL string is "static" in the language that embeds it. Technically, it will still be "dynamic" to the SQL engine, which doesn't know how the SQL string is constructed, nor that it was a static SQL string.
Dynamic SQL
Sometimes, the SQL string needs to be constructed dynamically, given some input parameters. E.g. the above query might not need any predicate at all in some cases.
You might then choose to proceed to constructing the string dynamically, e.g. in PL/SQL:
DECLARE
TYPE foo_c IS REF CURSOR;
v_foo_c foo_c;
v_foo foo%ROWTYPE;
sql VARCHAR2(1000);
BEGIN
sql := 'SELECT * FROM foo';
IF something THEN
sql := sql || ' WHERE x = 1'; -- Beware of syntax errors and SQL injection!
END IF;
OPEN v_foo_c FOR sql;
LOOP
FETCH v_foo_c INTO v_foo;
EXIT WHEN v_foo_c%NOTFOUND;
END LOOP;
END;
Or in Java / JDBC:
String sql = "SELECT * FROM foo";
if (something)
sql += " WHERE x = 1"; // Beware of syntax errors and SQL injection!
try (ResultSet rs = stmt.executeQuery(sql)) {
..
}
Or in Java using a SQL builder like jOOQ
// No syntax error / SQL injection risk here
Condition condition = something ? FOO.X.eq(1) : DSL.trueCondition();
for (FooRecord foo : DSL.using(configuration)
.selectFrom(FOO)
.where(condition)) {
..
}
Many languages have query builder libraries like the above, which shine most when doing dynamic SQL.
(Disclaimer: I work for the company behind jOOQ)
Is it something vendor specific?
The SQL-92 Standard has a whole chapter on dynamic SQL (chapter 17) but it only applies to FULL SQL-92 and I know of no vendor that has implemented it.
I think what's meant is that you should build the query dynamically before executing it. For your other questions this means that you should select the table name you need first and the use your programming language to build a second query for doing what you want (what you want to do in the other question isn't possible directly like you want).