Database link name expected when executing update for oracle database - java

I'm relatively new to coding and Java. I have an assignment where we build a GUI using JavaFX that interfaces with an oracle database with relevant data to be entered into our GUI product. In our GUI we are supposed to have an Update button which function is to update/alter a specific row in the database after making changes to the data in the GUI textfields/comboboxes. For my update action I have the button linked to I get the error java.sql.SQLSyntaxErrorException: ORA-01729: database link name expected. I have searched online for answers but I don't fully understand what this means and how to solve this issue. I set up my connection in the beginning of my code and included static Connection con; Statement stmt; earlier in my code. Any ideas/help would be appreciated
My code is below:
void updateEmp() {
try {
String updateQuery = "UPDATE employees SET firstname = '"
+ tfFirstName.getText() + "', lastname = '"
+ tfLastName.getText() + "', salary = "
+ tfSalary.getText() + ", title = '"
+ jobTitlesCbo.getValue() + "'";
/*if (getDeptNum(deptTitlesCbo.getValue()) > 0
&& getDeptNum(deptTitlesCbo.getValue()) < 6) {
updateQuery = updateQuery + ", departmentid = '"
+ getDeptNum(deptTitlesCbo.getValue()) + "'";
}*/
updateQuery = updateQuery + " WHERE employeeid = " + tfEmpID;
stmt.executeUpdate(updateQuery);
} catch (Exception e) {
System.out.println("Error: " + e.toString());
e.printStackTrace();
}
}

Related

JAVA & SQL database save changes

I am working on Java GUI application which connects to SQL database on localhost (I use XAMPP). When I change some entry, for example Age, I click on "Save changes", it is saved and changes are done in SQL database, but when I click on ">" or "<" to view next or previous person and then go back to the person, where I did changes, every entry is without changes in its initial state. But when I close the application and reopen it, all the changes which I made are done. This is part of the code where is mistake, I think. Thank you.
private void jButtonSaveChangesActionPerformed(java.awt.event.ActionEvent evt) {
try {
Statement stmt = con.createStatement();
try {
String query1 = "UPDATE list1 SET " +
"name ='" + jTextFieldName.getText() + "', " +
"surname ='" + jTextFieldSurname.getText() + "', " +
"age ='" + jTextFieldAge.getText() + "' " +
"WHERE ID = " + jLabelActualID.getText();
stmt.executeUpdate(query1);
} catch (Exception e) {
System.err.println(e);
}
} catch (Exception e) {
System.err.println(e);
}
}
Picture of application:
You are not closing, which can be done more safe and automatically with try-with-resources.
This means a commit might not have happened yet. There is an autocommit setting too.
String query1 = "UPDATE list1 SET " +
"name = ?, " +
"surname = ?, " +
"age = ? " +
"WHERE ID = ?";
try (PreparedStatement stmt = con.prepareStatement(query1)) { // Closes stmt.
stmt.setString(1, jTextFieldName.getText());
stmt.setString(2, jTextFieldSurname.getText());
stmt.setInt(3, Integer.parseInt(jTextFieldAge.getText()));
stmt.setString(4, jLabelActualID.getText());
int updateCount = stmt.executeUpdate();
} catch (SQLException | NumberFormatException e) {
System.err.println(e);
}
The same may hold (or may not hold) for the SQL connection.
Also one should use a PreparedStatement for security (SQL injection) and type safeness / escaping of backslash, quote in strings. As you see it is even more readable.
Another case is a second application accessing the database: it can use its own cache, thereby be a bit outdated.

storing tweets in mysql from streaming api using java

I'm using twitter4j's streaming API to collect tweets. I'm doing this on java platform. I'm getting a stream of tweets at console but can't store.
public void onStatus(Status status) {
try
{
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/twitterapi";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "twitterapi", "");
String query = " insert into tweets"
+ "(tweet_id,tweet_text,screen_name)" + " values"
+ "('" + status.getId() + "','" +
status.getText() + "', '" +
status.getUser().getScreenName() +"')";
Statement statement = conn.createStatement();
statement.executeUpdate(query);
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
System.out.println("onStatus #" + status.getUser().getScreenName() + " - " + status.getText());
}
Please consider every other thing to be correct since that's already working.
In your insert you have a different number of columns to values. You are not specifying the author_id.
In addition, as DaveH noticed, you're not actually running the SQL command against the server.

Search the MYSQL Database filtering using either first name or last name typed in JTextfield on JTable

I want to use either last name or first name to filter result shown on JTable from the database such that when i type either Nikola or Tesla in the JTextfield, the row with either of the names is filtered.
I have stored name as one field in the database i.e 'Nikola Tesla' when i type Nikola, it is working right and when i type Tesla it shows no result.
I have one field for name that stores both names.
I don't want to have separate First_Name and Last_Name field.
Please suggest what i should add on my code shown below:
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try {
String selected = (String) jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate", "root", "");
String sql = "SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n"
+ "certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE " + selected + " LIKE ? ORDER BY stuff.Emp_Name\n";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText() + "%");
ResultSet rs = pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
You need to add % before the jTextFieldSearch.getText() also. See below
pstmt.setString(1, "%" + jTextFieldSearch.getText() + "%");
The true solution is this, you should to use %% inside quots '%%', without quotes you get that error:
LIKE '%Name%'
so, with prepared statement we should to change Name with ? and the result is like that:
String sql = "SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n"
+ "certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE " + selected + " LIKE '%?%' ORDER BY stuff.Emp_Name\n";
i hope this can help you, good luck.

Simple JDBC SQL Query returns an empty ResultSet

I have been trying to get a plugin I am working on to talk to my SQL database, creating tabels, and adding rows seems to work fine but simple SELECT queries are returning an empty ResultSet. The relevant code is below.
queryL=
"SELECT RATING"
+ " FROM USERS"
+ " WHERE UUID = '"
+ UUID +"';";
queryG=
"SELECT RATING"
+ " FROM " + Constants.serverName
+ "_USERS"
+ " WHERE UUID = '"
+ UUID +"';";
try {
stmt=con.createStatement();
rs=stmt.executeQuery(queryL);
if (rs.next()){
r.setLocalRating(rs.getInt(1));
}else{
r.setLocalRating(0);
registerPlayer(UUID,false);
Dungeon.getPlugin(Dungeon.class).log("Player new to server");
}
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
stmt=con.createStatement();
rs=stmt.executeQuery(queryG);
if (rs.next()){
r.setGlobalRating(rs.getInt(1));
}else{
r.setGlobalRating(0);
registerPlayer(UUID,true);
Dungeon.getPlugin(Dungeon.class).log("Player new to network");
}
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As you can see if the ResultSet is empty (player does not yet exist in my database) I call registerPlayer. Register player then throws a duplicate entry for primary key error, so I know the table and the row I am looking for exist.
The following code shows the update queries used inside the registerPlayer method.
if (global){
query=
"INSERT INTO"
//+ Constants.dbName + "."
+ " USERS"
+ " VALUES ('"
+ UUID + "', 0)";
}else{
query=
"INSERT INTO "
//+ Constants.dbName + "."
+ Constants.serverName
+ "_USERS "
+ "VALUES ('"
+ UUID + "', 0)";
}
Finally for completeness, the queries used for creating the tables
String userLocalTable=
"CREATE TABLE IF NOT EXISTS " //+ Constants.dbName + "."
+ Constants.serverName +
"_USERS " +
"(UUID varchar(36) NOT NULL, " +
"RATING int NOT NULL, " +
"PRIMARY KEY (UUID))";
String userGlobalTable=
"CREATE TABLE IF NOT EXISTS " + //Constants.dbName + "."
"USERS " +
"(UUID varchar(36) NOT NULL, " +
"RATING int NOT NULL, " +
"PRIMARY KEY (UUID))";
Any insight into my issue would be greatly appreciated, as far as I can tell the SELECT queries should not be returning empty ResultSets.
Thanks for the input, turns out it was something obvious staring me in the face, QueryL's and QueryG's respective queries needed to be swapped.

MySQL Error [1064] in Updating a Database

At the moment I am writing a small program which should check whether a file is in a database and if its SHA264 is correct. If it is not correct it should be updated in the database.
The function which I have written for updating are the following:
public static void updateSHA(String TABLE, String shaOLD, String shaNEW)
{
boolean success = false;
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
PreparedStatement prepStatement = null;
String update = "SET SQL_SAFE_UPDATES = 0" + "; \n" // if I remove this line resp. "'SET SQL_SAFE_UPDATES = 0' + '; \n' + " I get another error code, see below
+ "UPDATE " + dbName + "." + TABLE + " SET sha256 = '" + shaNEW + "' WHERE sha256 = '" + shaOLD + "'" + ";";
try
{
con = DBConnection();
con.prepareStatement(update);
statement = con.createStatement();
resultSet = statement.executeQuery(update);
con.commit();
System.out.println("Successfully updated " + shaOLD + " to " + shaNEW + " in " + dbName + "." + TABLE);
success = true;
}
catch (SQLException sqle)
{
System.out.println(update);
System.out.println("Error at updateSHA for " + shaOLD + ": " + "[" + sqle.getErrorCode() + "] " + sqle.getMessage());
}
finally
{
if (con != null)
{
try
{
con.close();
}
catch (SQLException sqle)
{
System.out.println("Error at updateSHA for " + shaOLD + " while closing con: " + "[" + sqle.getErrorCode() + "] " + sqle.getMessage());
}
}
if (statement != null)
{
try
{
statement.close();
}
catch (SQLException sqle)
{
System.out.println("Error at updateSHA for " + shaOLD + " while closing statement: " + "[" + sqle.getErrorCode() + "] " + sqle.getMessage());
}
}
if (!success)
{
System.exit(-1);
}
}
}
An example of an update query:
SET SQL_SAFE_UPDATES = 0;
UPDATE databaseName.tableName SET sha256 = '4e89f735c019ab1af439ec6aa23b85b66f2be1a1b15401b2471599d145cfda42' WHERE sha256 = '000c675c73567f4256c7de7ad7c43056d5f002e08c1a5c7b4ff77a4dd8e479a3';
The exact error is:
Error at updateSHA for 000c675c73567f4256c7de7ad7c43056d5f002e08c1a5c7b4ff77a4dd8e479a3: [1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE databaseName.tableName SET sha256 = '4e89f735c019ab1af439ec6' at line 2
I think it has something to do with the "new" sha which should replace the old one (because in the error it looks like the sha gets cut off or something like that).
If I copy and paste the above update query in MySQL Workbench I do not get any errors and everything works fine (the entry gets updated).
If I delete the line 'SET SQL_SAFE_UPDATES = 0" + "; \n' I get the following error code:
Error at updateSHA for 000c675c73567f4256c7de7ad7c43056d5f002e08c1a5c7b4ff77a4dd8e479a3: [0] Can not issue data manipulation statements with executeQuery().
An assumption is, that the second error occurs because of the MySQL safe update mode.
So my question: Why do I get the 1064 error reps. why does the new sha get cut?
You are trying to execute two statements in one statement execute. This is not allowed by JDBC. Technically the MySQL JDBC driver has a connection property to allow this, but it is disabled by default (as the behavior violates the JDBC spec). You need to split it into two queries. Note however that the default for SQL_SAFE_UPDATES already is 0.
See allowMultiQueries in Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J if you really need to execute two queries as one statement.
The second part of your problem (after removing the SET SQL_SAFE_UPDATES = 0;) is that you are trying to use executeQuery to execute a statement that does not produce a ResultSet. That is not allowed. You should use executeUpdate (or execute) instead.

Categories