SyntaxError Exception - mysql

#Override
public void start(Stage primaryStage) throws Exception{
try{
String fxmlName;
Connection con = DriverManager.getConnection("url","root","password");
Statement st = con.createStatement();
String qry = "select UpdateT from schema.update";
ResultSet rs = st.executeQuery(qry);
fxmlName = rs.getString("UpdateT");
// System.out.println(fxmlName);
st.close();
Parent root = FXMLLoader.load(getClass().getResource(fxmlName));
primaryStage.setScene(new Scene(root));
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
}
catch (Exception e){
System.out.println(e);
}
}
Hey guys this is my code and its my first time on stack overflow and why I am getting this exception?
java.sql.SQLException: Before start of result set

UPDATE is a reserved word, so your DB objects should not use it. You can:
change the table name (i 'd prefer this)
use quotes every time to refer to that table

Related

how can i connect to my database sql in a java class method and called it in another class?

i'm trying to create a desktop application using corba and java swing for graphical interface.
As you know , in CORBA we have to make the principal methods like: connecting to the database ,calculations... in the server ,so i have created a method in a server class for connecting to the database.
The java class method is the one shown bellow:
public void connect_db(){
// TODO Auto-generated method stub
JTextField txtUsername = FrameLogin.txtUsername;
JPasswordField pwd= FrameLogin.pwd;
JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root", "Mrayhana123");
Statement stm = conn.createStatement();
String sql="select * from etudiant where username='"+txtUsername+"' and pwd='"+pwd+"'";
ResultSet result = stm.executeQuery(sql);
if(result.next()){
lblLoginMessage.setText("you are connected");
lblLoginMessage.setForeground(Color.GREEN);
}
else {
lblLoginMessage.setText("Incorrect username or password!");
lblLoginMessage.setForeground(Color.RED);
}
} catch(Exception e){
//System.out.println("not connected to database");
e.printStackTrace();
}
}
And i have called it in the client class which contain the graphical interface by the following way:
public static JTextField txtUsername;
public static JPasswordField pwd;
public static JLabel lblLoginMessage = new JLabel("");
pnlBtnlogin.addMouseListener(new MouseAdapter() {
#Override
String username = txtUsername.getText();
String pwd= pwd.getText();
try {
SraCorbaImpl sci = new SraCorbaImpl();
sci.connect_db();
} catch(Exception e1){
//System.out.println("not connected to database");
e1.printStackTrace();
}
But the result always shows me Incorrect username or password! even though I type a username and a password which are in the database.
THANK YOU FOR HELPING ME
According to your comment, I understand that you are successfully connecting to the database but your query is not returning any rows.
If the code in your question is your actual code, then you are passing a JTextField to your [SQL] query and not the text of the JTextField. Likewise with the password. You are passing the JPasswordField and not the actual password.
Try the below code.
public void connect_db(){
JTextField txtUsername = FrameLogin.txtUsername;
JPasswordField pwd= FrameLogin.pwd;
JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
try {
// Class.forName("com.mysql.cj.jdbc.Driver"); <- not required
Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root", "Mrayhana123");
Statement stm = conn.createStatement();
String sql="select * from etudiant where username='"+txtUsername.getText()+"' and pwd='"+pwd.getText()+"'"; // Change here.
ResultSet result = stm.executeQuery(sql);
if(result.next()){
lblLoginMessage.setText("you are connected");
lblLoginMessage.setForeground(Color.GREEN);
}
else {
lblLoginMessage.setText("Incorrect username or password!");
lblLoginMessage.setForeground(Color.RED);
}
} catch(Exception e){
//System.out.println("not connected to database");
e.printStackTrace();
}
Because you are using string concatenation, the toString of JTextField is being inserted into your SQL string.
Consider using a PreparedStatement instead.
String sql="select * from etudiant where username=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, txtUsername.getText());
ps.setString(2, pwd.getText());
In that case, if you omit the .getText(), the code will not compile.

Does h2 have a query/clause similar to the WHERE IN in MySQL?

My code currently goes as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
String[] data = parentIds.toArray(new String[parentIds.size()]);
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (?)";
stmt = conn.prepareStatement(sql);
data = parentIds.toArray(data);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
However even though in the unit tests I try to pass an array with parentIds, the return remains null.
What I can gauge from this is one of the following:
The array data isn't getting properly read, therefore the output is coming as null.
WHERE IN is not supported by h2 or else there is a different implementation that needs to be used instead.
Where am I going wrong in this?
EDIT - There was a similar duplicate question that was tagged. While it suggested using a StringBuilder and a loop, I was looking for an answer stating how it could be done in a cleaner way using the query itself.
Try setting the parameter as a list instead of an array, ie replace
stmt.setObject(1, data);
with
stmt.setObject(1, Arrays.asList(data));
Figured it out.
There was an issue posted on the h2database GitHub about this exact problem. Followed the suggested edits and it worked!
Code after edits is as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
Object[] data = parentIds.toArray();
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (SELECT * FROM TABLE(x VARCHAR = ?))";
stmt = conn.prepareStatement(sql);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
As you can see, I've used an Object array for data instead and added an additional query inside the main query.
Followed the instructions given in the GitHub issue to a tee and it worked flawlessly.

SQL result convert into integer

I'm having trouble convert this String sql results into int. Can you guys tell how to accomplish this.
I'm doing this because I need this value set in to a JLabel that shows attendance count.
I've tried to search for the answer here, but I couldn't find it. Please can you guys help me with this problem?
public static int attendanceCount() throws ClassNotFoundException, SQLException {
String sql = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
return rst; // How do I convert this into integer?
}
This is what I need to accomplish.
private void setAttendanceTile() {
try {
int attendanceCount = AttendanceController.attendanceCount();
inHouseMembersLabel.setText(Integer.toString(attendanceCount));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
Or is there another way to accomplish this without doing this way?
Thanks.
get ResultSet.getInt(1):
int id = rst.getInt(1);
You could use ResultSet.getInt() method. It takes either a column index or a column name. Here's an example from Oracle.
In your case you would need the one which takes the index (note that index starts with 1, not 0).
As suggested earlier, try using .getInt() method.
Moreover, I would use PreparedStatement. It's important to use PreparedStatement, because it allows database to cache your queries.
Also, always close your Connection and ResultSet after using them.
public static int attendanceCount() throws ClassNotFoundException, SQLException {
final int COLUMN_NO = 1;
final String SQL = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
PreparedStatement stm = conn.prepareStatement(SQL);
ResultSet rst = stm.executeQuery();
int result = rst.getInt(COLUMN_NO);
try {
rst.close();
conn.close();
} catch (SQLException e) {} //ignore
return result;
}

hibernate multiple update queries single transaction

I am using hibernate with mysql db but having trouble with multiple updates in single transaction
Here is my code
public void updateOEMUser(OEMUserDetailsDTO userDTO) throws Exception{
Session session = GCCPersistenceMangerFactory.getSessionFactory().openSession();
Transaction tx = null;
try{
String query = "update oemuserdata set full_name=\""+userDTO.getFullName()+ "\" ,contact_no=\""+userDTO.getContactNo() + "\" where user_id="+userDTO.getUserId();
String query1 = "update usermasterdata set account_status="+userDTO.getAccountStatus() + " ,user_name=\"" + userDTO.getUserName() + "\" where user_id="+userDTO.getUserId();
Query q = session.createSQLQuery(query);
Query q1 = session.createSQLQuery(query1);
tx = session.beginTransaction();
q.executeUpdate();
q1.executeUpdate();
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
throw new RuntimeException("HibernateException_updateOEMUser");
}finally {
session.close();
}
}
The code works but when I make "q1.executeUpdate()" fail the record in "oemuserdata" is getting locked in Mysql.
Am I doing something wrong?
Try using such kind of pattern.
StringBuilder query = new StringBuilder();
query.append("UPDATE CLASSNAME_FIRST a ,");
query.append("CLASSNAME_SECOND b,");
query.append("SET a.full_name='"+userDTO.getFullName()",");
.....
int var = stmt.executeUpdate(query);
Ok I didin't find the solution but I found out what's happening here.
When I remove the connection after successful execution of q.executeUpdate() exception is thrown at the execution of q1.executeUpdate() and after catch block it goes in final block and tries to execute session.close(), but since there is no DB connectivity this also fails.
But Mysql still has the lock requested by q.executeUpdate(). That's why the row is locked until Mysql releases lock itself.

Store the results of ResultSet in a list

My goal is to centralize all the interactions with my MySql database in a single class (e.g. SqlUtils). I basically want to maintain access to ResultSet or a similar class even after the connection is closed. The following way doesn't work as after my business method receives the ResultSet, an exception is thrown because the underlying connection is already closed. I want to emphasize that opening and closing a connection to the database has to take place inside getResultSet().
public ResultSet getResultSet(String sql) {
try (Connection conn = getConnection();){
return conn.createStatement().executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
What I'm now thinking to do is something like this:
public List<ResultHolder> getResultSet(String sql) {
List<ResultHolder> list = new LinkedList<>();
try (Connection conn = getConnection();
ResultSet res = conn.createStatement().executeQuery(sql);) {
while(res.next()) {
list.add(res.convertToResultHolder());
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
Is there any class that does what I need, which I expressed as ResultHolder.
If you want to have access to all the resultset data even after connection is closed then I would suggest following:
public List<Map<String, Object>> getResultSet(String sql) {
// this list will hold all the data returned from resultset
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
try (Connection conn = getConnection();
ResultSet rs = conn.createStatement().executeQuery(sql);) {
while(rs.next()) {
// this map corresponds to each row of the resultset
// key: column-name, value: column-value
Map<String, Object> row = new LinkedHashMap<String, Object>();
// populate each row using resultset's Meta data
ResultSetMetaData meta = rs.getMetaData();
for (int i=1; i<=meta.getColumnCount(); i++)
row.put(meta.getColumnName(i), rs.getObject(i));
rows.add(row);
}
} catch (Exception e) {
e.printStackTrace();
}
return rows;
}