Create a sql sequence programmatically in Java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to create a sql sequence in sql server programmatically from Java and I should be able to retrieve the continuous value from the sequence to program. First of all can I do so? If so how?

It's possible as all SQL servers provide some functionality and guarantee ACID rules. Even with very simple old MySql engine which didn't support transactions it's achievable. The easiest and widely supported approach is:
CREATE TABLE SequenceValue (
sequenceIdentifier varchar(124) NOT NULL PRIMARY KEY,
sequenceValue INT NOT NULL;
);
All you need to do in the program is:
Connection con = dataSource.getConnection();
try {
con.setAutoCommit(true);
PreparedStatement st = con.prepareStatement("SELECT sequenceValue SequenceValue WHERE sequenceIdentifier = ?");
st.setString(1, sequenceIdentifier);
SQLException retried = null;
for (;;) {
ResultSet rs = st.executeQuery();
if (!rs.next()) {
if (retried != null)
throw retried;
PreparedStatement ins = con.prepareStatement("INSERT INTO SequenceValue (sequenceIdentifier, sequenceValue) VALUES (?, ?)");
ins.setString(1, sequenceIdentifier);
ins.setLong(2, 0);
try {
ins.executeUpdate();
}
catch (SQLException ex) {
// store the exception and rethrow if next query retry fails
retried = ex;
}
}
else {
long value = rs.getLong(1);
PreparedStatement upd = con.prepareStatement("UPDATE SequenceValue SET sequenceValue = sequenceValue+1 WHERE sequenceIdentifier = ? AND sequenceValue = ?");
upd.setString(1, sequenceIdentifier);
upd.setLong(2, value+1);
if (upd.executeUpdate() == 1)
return value+1;
}
}
}
finally {
con.close();
}
Briefly: The code avoid transactions completely. At the beginning it tries to retrieve the sequence value according to identifier. In case it's not found, it attempts to create it and retries retrieving again. It doesn't fail in case the value was created in the meantime.
If the value is found, it tries to increment it using atomic update on the row. If it succeeds then it returns the incremented value, if not it retries again.

Related

How to perform an update query in Java? [duplicate]

This question already has an answer here:
What is wrong with this update query in java?
(1 answer)
Closed 7 years ago.
I am not so into database and I have the following problem in a Java application that have to perform a very simple query that update a field on a table of my DB.
So, the original query is something like this:
UPDATE coda_tx c SET c.FK_STATO = 2 WHERE c.PK_CODA = 62816;
so I have implemented the following Java method that implement the previous query, this one:
public void updateStatus(int pkCoda, int newStatus) {
String sql;
StringBuffer sb = new StringBuffer();
sb.append("UPDATE coda_tx c SET c.FK_STATO = ");
sb.append(newStatus);
sb.append(" WHERE c.PK_CODA = ");
sb.append(pkCoda);
sql = sb.toString();
try {
statment = connection.createStatement();
ResultSet rs = statment.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
My only doubt is related about the section by which the query is performed, this one:
statment = connection.createStatement();
ResultSet rs = statment.executeQuery(sql);
I think that this is wrong because actually there is ResultSet that is an object used to retrieve rows by a SELECT operation. In this case I am updating a field of a specific row and I am not retrieving rows putting theme into a ResultSet object.
So, how can I correctly handle this situation? How have I to perform my query?
Here is how you could do it:
// updateCount contains the number of updated rows
int updateCount = statment.executeUpdate(sql);
You are looking for statement.executeUpdate() which will return the number of rows affected by the update.
int executeUpdate(String sql) throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Reference: http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
If your method recives for example two variables like fkStato and pkCoda, that contains the value you want, you can make a simple query:
int fkStato=2;
int pkCoda=62816;
try
{
// create our java preparedstatement using a sql update query
PreparedStatement ps = conn.prepareStatement(
"UPDATE coda_tx c SET c.FK_STATO = ? WHERE c.PK_CODA = ?;");
// set the preparedstatement parameters
ps.setInt(1,fkStato);
ps.setInt(2,pkCoda);
// call executeUpdate to execute our sql update statement and returns number of rows affected
int updateCount = ps.executeUpdate();
ps.close();
}
catch (SQLException se)
{
// log the exception
throw se;
}

How to easy upload content to MySql database in Java using JDBC? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m beginner and I have problems with using MySql in Java with JDBC.
Can anybody paste a lines of code how to use “SQL UPDATE”.
Or maybe someone know about some good tutorials to learn it?
My code with mistakes:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
ResultSet ra = st.executeQuery(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
For executing UPDATE/INSERT/CREATE statements you should use execute() function of Statement class and not executeQuery().
Corrected code :
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
st.execute(strUpdate); // or use executeUpdate()
It will return a boolean value that you can check and proceed.
follow this example here but this is essentially it
String strUpdate = "UPDATE rozchody SET nazwa ='test'";
PreparedStatement preparedStatement = conn.prepareStatement(strUpdate);
// execute insert SQL stetement
preparedStatement.executeUpdate();
When you want to do a UPDATE,INSERT,DELETE on a SQL database, you never receive a resultset.
Use executeUpdate instead of executeQuery.
Only one ResultSet object can be opened for a Statement. You're creating two ResultSet objects with your UPDATE and then your SELECT statements.
Since UPDATE does not return a ResultSet, use st.execute(strUpdate). Then you can retrieve a ResultSet with st.executeQuery("select * from rozchody");
Your fixed code:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
//Change this
st.execute(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
//Now you won't get an error opening a new ResultSet
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
Note that while the above will work, it is generally better to use PreparedStatements rather than re-using a Statement for different executions. This will help prevent SQL injection, and you should read into it once you have a firmer grasp on how the Statement object works.

Which of this delete JTable row methods is better? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have two kind of methods to remove JTable selected row.
I create this methods in my GUI Class:
First:
public void dellAction() {
if (table.getSelectedRow() > -1) {
int rowToDelete = table.getSelectedRow();
int rowToModel = table.convertRowIndexToModel(rowToDelete);
Object rowId = table.getValueAt(rowToModel, 0);
try {
Connection con;
PreparedStatement ps = null;
con = DriverManager.getConnection(...);
ps = con.prepareStatement("delete from table where id=?");
ps.setObject(1, rowId);
if (ps.executeUpdate() == 1) {
model1.removeRow(rowToModel);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
} else JOptionPane.showMessageDialog(null, "Select A Row");
}
Second:
public void delete(DefaultTableModel model, int modelRow) {
if (table.getSelectedRow() > -1) {
Object rowId = model.getValueAt(modelRow, 0);
try {
Connection con;
PreparedStatement ps = null;
con = DriverManager.getConnection(...);
ps = con.prepareStatement("delete from table where id=?");
ps.setObject(1, rowId);
if (ps.executeUpdate() == 1) {
model.removeRow(modelRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
}
The question depends on the context of your application. In a perfect world, your TableModel would be modelling data from some kind of factory/controller that was responsible for managing the data, which would read/write to some kind of data source.
This would allow your TableModel the opportunity to simply not care where the data was coming from or going to, only that it had some means of performing these actions.
The same would go for your JTable, it should have no idea about the source of the data, only that the TableModel provides the required contract it needs to fulfill its responsibility.
This, then, raises the question of, who should actually perform what jobs.
In this scenario, I would provide some means for the factory/controller to alert registered listeners to changes. This would decouple the API in such away that any part of the program would then be able to modify the factory/controller without needing to know about everybody else who might be using that factory/controller, but still be able to react to those changes.
So, my answer would generally be neither...but...your second one comes closest to achieving this, but I'm concerned about the need to extract data from the model in this way, but that's me...
This is, of course, is just my opinion, based on the factory, observer, producer-consumer and model-view-controller patterns

insert repeated when i execute programm [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Hi i have code java swing to insert 2 lines in tables sql
and i insert in table 2 jtextfields that i set in frame
So i want don't insert line if i set the same text in jTextfields
this is the code:
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db, "root", "123456");
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO router(hostname,address,version)VALUES('Edge 01','"+jTextField1.getText()+"','2700')" ) ;
stmt.executeUpdate("INSERT INTO router(hostname,address,version) VALUES('Edge 02','"+jTextField2.getText()+"','2700)" ) ;
stmt.close();
conn.close();
}
catch(SQLException ek){
}
Thank you
There are two possible options:
Try retrieving the record using select statement and insert only when if select results into ZERO records.
Create a unique key/index on the database table columns and let the inserts trigger. Insert will fail in case of duplicates but you need handle the exceptions (duplicate/unique).
If possible, apply both the steps together otherwise select one of the steps better suiting your other business scenarios.
I would suggest that you never, ever, build queries at Strings. Use a PreparedStatement.
Now, with that out of the way. You need to first query the database to see if it contains the desired value, if it doesn't insert it.
Move this logic into a separate method for clarity. And always close resources in a finally block, otherwise you get a memory leak if there is an Exception. I have used the Java 7 try-with-resources construct.
public boolean insertIfNotPresent(final Connection con, final String value) throws SQLException {
final String checkQuery = "SELECT COUNT(*) FROM router where hostname='Edge 01' and version=2700 and address=?";
try (final PreparedStatement statement = con.prepareStatement(checkQuery)) {
statement.setString(1, value);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next() && resultSet.getInt(1) > 0) {
return false;
}
}
}
final String insertQuery = "INSERT INTO router SET hostname='Edge 01', version=2700, address=?";
try (final PreparedStatement statement = con.prepareStatement(insertQuery)) {
statement.setString(1, value);
statement.executeUpdate();
}
return true;
}
So the first query, SELECT COUNT(*) ..., counts rows matching the criteria. If there is already something in the database we return false.
The second query does the insert if we didn't return false from the first part. The method returns true in this case.
As an example in the above code, something like the following would work
try(final Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db, "root", "123456")) {
insertIfNotPresent(conn, jTextField1.getText());
insertIfNotPresent(conn, jTextField2.getText());
}

can i write my Sql query in this way [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am wondering can i insert table name in this format
String update = "UPDATE ? SET Status = ? WHERE Name = ?";
stmt.setString(1,tableName);
stmt.setString(2,status);
stmt.setString(3,name);
same for insert and delete statements?
No.
The reason you place question marks in the query (aside from protection against SQL injection) is so that the database can prepare the statement once and use that prepared statement with different parameters. It wouldn't be able to prepare a statement if it doesn't know what table(s) you are using.
The short answer is no. But you can do it this way:
String update = "UPDATE " + tableName + " SET Status = ? WHERE Name = ?";
...
stmt.setString(1,status);
stmt.setString(2,name);
Be aware of the SQL injection though. Be sure your tableName comes from the secure source.
Normally, you would do this as shown below...
String sql = "UPDATE " + tableName " SET Status = ? WHERE Name = ?";
PreparedStatement stmt = null;
try {
stmt = connection.prepareStatement(sql);
stmt.setString(1, status);
stmt.setString(2, name);
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
No you cann't do this because you are definitely using a prepared statement. The reason you can not do this is PreparedStatement is pre-compiled so it needs the table which you are modifing (its data using DML) or structurally (using DDL). If you don't mention the table table name how the statement is going to be pre-compiled?
If you want you can use dynamic SQL but in that case you don't have to use PreparedStatement you can use it using a simpler implementation Statement.
Hope this is helpful !!

Categories

Resources