running sql update query in java swing - java

I have a swing desktop application that is
connected to a derby DB.
I use native sql query to select all data from the table
Now I want to update the data in the table with native sql queries
but first I have to retrieve the input data from the swing textfields.
I am able to use the jtextfielld.gettext()
to retrieve that data but how do i set these textfields data to
the update query since the sql query is executed as a string statement.
for example :
String sql = "UPDATE APP.REGISTRY SET LETTER_FROM ='Japan Motors' WHERE id = 7"
so how do execute this query from the swing interface.
Please help.

Have you looked at PreparedStatements ?
Although PreparedStatement objects can be used for SQL statements with
no parameters, you probably use them most often for SQL statements
that take parameters. The advantage of using SQL statements that take
parameters is that you can use the same statement and supply it with
different values each time you execute it.
See the linked doc and note in particular the placeholder capability (using ?s) that allows you to safely insert parameters in your SQL.

It appears you are new to JDBC and looking for a way to execute queries form Swing App. If this is a case, I will refer you to look at JDBC documentation.
In essence, you will need to get a reference to Connection object, then create a PreparedStatement using the connection and then then you can call executeUpdate() method followed by commit() method.
However, Please understand that you have very limited options for getting connection in a swing app. You will need to look at the usage of DriverManager for the way to get connection for a database.

Related

Ways to get mysql(innodb) AUTO_INCREMENT Column, JDBC/getGeneratedKeys()/last_insert_id (in OkPacket) and LAST_INSERT_ID()

According to mysql doc:
https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-last-insert-id.html
At times, it can be tricky to use the SELECT LAST_INSERT_ID() query,
as that function's value is scoped to a connection. So, if some other
query happens on the same connection, the value is overwritten. On the
other hand, the getGeneratedKeys() method is scoped by the Statement
instance, so it can be used even if other queries happen on the same
connection, but not on the same Statement instance.
First, I consider LAST_INSERT_ID().
The SQL function LAST_INSERT_ID() is connection safe, but not session/transaction/statement safe. It can't be used in production, because in real environment multiple session/transaction/statement in one connection is very common.
Then getGeneratedKeys() using JDBC. When I'm using getGeneratedKeys() in Java. I want to see what it does in database. I try to track the SQL statement with the following statements after a simple insert into a demo table with auto increase primary key using JDBC:
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
SELECT * FROM mysql.general_log;
I'm sure the new row is correctly inserted and getGeneratedKeys() brings the auto-incremented id back. However, I find nothing but just an insert statement which JDBC executed before, and some static data like "SELECT database(),version()...".
Now, conclusion is, getGeneratedKeys() doesn't execute any SQL statement to get auto-incremented id. Then I find another possibility, I debug into call stacks, see JDBC get auto-incremented id from an object called OkPacket. It has a property called last_insert_id. Here I find it finally.
My questions are:
Is there really no way to get a STATEMENT SAFE (at least transaction safe) auto-incremented id using pure SQL statement (without JDBC)?
How does OkPacket work under hood? How does it get a statement safe auto increased id? Maybe it calls some low level C function in MySQL driver or MySQL server/client protocol?
MySQL has an API that clients use to communicate commands and get results.
Actually, it has two forms of this API. One is called the "SQL protocol" in which statements are sent as strings like SELECT * FROM mytable, etc. The other form is called the "binary protocol" where commands are sent using some byte that the server recognizes, even though they are not human-readable strings.
Some commands can be executed by either the SQL protocol or the binary protocol.
For example, START TRANSACTION, COMMIT, PREPARE... there are textual SQL statements for these commands, but there are also non-textual ways for the API to invoke these commands.
You can certainly query SELECT LAST_INSERT_ID(); and get the most recent generated id, but only the most recent. Another INSERT statement will overwrite this value, as you read.
The OkPacket is filled in by the binary protocol. That is, the MySQL Server returns an OkPacket with several pieces of metadata about any statement execution.
See https://github.com/mysql/mysql-connector-j/blob/release/8.0/src/main/protocol-impl/java/com/mysql/cj/protocol/a/result/OkPacket.java#L55
The Ok Packet includes the following:
Affected row count (if any)
Last insert id (if any)
Status flags
Warning count (if any)
String with error message (if any)
The MySQL Server code that documents the OK Packet is unusually thorough with examples:
https://github.com/mysql/mysql-server/blob/8.0/sql/protocol_classic.cc#L665-L838
There's no way to fetch the OK Packet for earlier SQL statements. The client must save the result immediately after a statement execution. In object-oriented code such as the JDBC driver, it makes sense to store that in the NativeResultset object: https://github.com/mysql/mysql-connector-j/blob/release/8.0/src/main/protocol-impl/java/com/mysql/cj/protocol/a/result/NativeResultset.java#L77-L82

Memcache implementation design

Iam trying to implement memcache in my web application and just wanted to get suggestions that whether what iam doing is right in terms of design.
I have a class SimpleDataAccessor which run all my insert, update and select sql queries. So any query that has to be performed is executed inside the method of this class.
So inside the method where I have my select query implementation i have a method which stores the resultset in memcache like this.
storeinMC(resultset.getJSON(),sqlquery);
the sqlquery here is my key.
Also before running the selectquery i check in memcache that whether I have a resultset already for that query.
if((String res=getRSFromMC(sqlquery)==null)
So i've tried to keep it plain and simple.
Do you see any issues with this.?
As rai.skumar rightfully pointed out your SQL statements could be constructed differently (e.g. WHERE clause could contain same conditions in diff order, etc.)
So to overcome above mentioned issues, you need to parse your SQL and get all the relevant pieces from it. Then you can combine these pieces into a cache key.
You can take a look at SQL parsers: ZQL, JSqlParser, General SQL Parser for Java that return you java classes out of your SQL.
Another option would be to use JPA instead of straight JDBC. For example Hibernate has great JPA support and fully capable of caching your queries.
If you feel closer to JDBC you could use MyBatis that has very JDBC like syntax and caching support.
Consider below queries:
String k1 = "Select * from table"; //Query1
String k2 = "Select * from TABLE"; // Query2 ; notice TABLE is in caps
Both of above SQL queries are same and will fetch same data. But if above queries are used as keys in Memchached they will get stored at different places ( as k1.equals(k2) will return false).
Also if somehow you can ensure that there are no typos or extra spaces, it won't be very efficient as keys/queries could be very big.

How to print used SQL query when using PreparedStatement (JDBC)

I used PreparedStatement in my Java program. I need to debug the SQL query because it's not working fine.
Is there is away to print the used SQL statement with the values inserted
for example in PreparedStatement:
select * from table where a=?
and than I set the ?
could I print the used SQL, for example:
select * from table where a=1
It can't be done with java.sql.PreparedStatement interface itself; it depends on the implementation by your database vendor.
But you're in luck; the MySQL driver allows you to do it using its toString implementation:
http://www.avajava.com/tutorials/lessons/how-do-i-display-a-prepared-statement-with-bind-variables-using-mysql.html
You need to be aware that using this vendor-specific feature binds your code to MySQL. You can't change databases without changing your code.

Can you put multiple statements in one query-string in Oracle jdbc?

I have a JDBC connection to an Oracle database. I create a Statement. The SQL query String contains multiple statements separated by a semicolon, and is provided by a different system.
Example:
connection.prepareStatement("SELECT * FROM A; SELECT * FROM B");
According to ddimitrov it isn't possible.
But all other databases I've tried support it. And JDBC even has support to retrieve multiple results.
Does anyone have either pointers to Oracle documentation explicitly stating that it is not supported or have a way to make it work (without using of stored procedures)?
For executing multiple statements:
JDBC 2.0 lets you submit multiple statements at one time with the addBatch method
See here.
No, this is not possible with the Oracle JDBC driver.
You will have to parse and split the string into their individual statements.
Btw: I think the only databases that allow this are Microsoft SQL Server and MySQL. Which also makes them vulnerable to certain kind of SQL injection attacks that would not work Oracle or PostgreSQL.
AFAIK most databases only allow you to execute / prepare one statement per execute or prepare call. Although not very explicitly expressed, the intent of the JDBC methods is to execute a single SQL statement:
sql - **an** SQL statement that may [...]
The retrieval of multiple resultsets is for (very rare) single(!) statements or stored procedures which return multiple resultsets (as explained in the javadoc of Statement#execute).

how to get insert sql in mysql shell or java library?

my table is:
[tableAbc]
A B C
------------
1 a b
2 c e
3 e r
...
run:
show create table tableAbc;
to get the create table sql
but how to get insert sql?
like:
insert into `tableAbc` ('A','B','C') VALUES(1,'a','b');
...
any idea? (or any java library to do this)
thanks all!
BTW:
i want show the "insert sql" to web brower.
so,i think i need get "insert sql" under java, or sql commands.
If you use Squirrel (A SQL tool) it can generate this for you.
I use this tool daily (it is free and it works well)
As per their description
SQuirreL SQL Client is a graphical
Java program that will allow you to
view the structure of a JDBC compliant
database, browse the data in tables,
issue SQL commands etc,
To get the insert statement for a table just right click on a table and select "data scripts"
Your question is difficult to understand due to everything being in sentence-fragments, but I think you're basically just looking for a way to be able to send SQL statements to your SQL database from Java, specifically an insert statement?
If this is the case, Java has an sql package. You can create a connection to your database, create a statement, and execute it. This will then return a ResultSet which is the result of the executed statement. Start here perhaps? http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#createStatement%28%29 And there is part of an example on the documentation for ResultSet http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html
What do you mean by "i want to show the insert sql in the browser"? Do you mean you want to show what the result of the executed statement is?

Categories

Resources