I would like to execute code with a database query - java

I would like to make a mysql database query in a Java code and if the value from the database is true for example then a certain code should be executed and if the value is false the program should close but I have the problem that I get the value from the database is not formatted so that I can make an IF query. if I could not explain this in a very understandable way, I hope that you can find out from the code in the appendix
//imports
package de.alphaalmann.troll;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.*;
public class Main extends JavaPlugin {
public static void main(String[] args) {
//databaseconnetion
String url = "jdbc:mysql://localhost/plugin?useJDBC";
String user = "plugin";
String password = "uwu3000";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("sucsesful");
PreparedStatement stmt = conn.prepareStatement("SELECT STATUS FROM plugin WHERE NAME="trollpl"");
stmt.execute();
System.out.println(stmt);
stmt.close();
//if-query if it true,
if(stmt==true) {
//if it true execute this
//else this part
}else {
System.out.println("error");
}
}catch(SQLException ex) {
System.err.println(ex.getMessage());
}
}
}

highling.
You'll need a ResultSet object in order to receive the query results, get the results and then close the PreparedStatement.
Something like this:
int result;
ResultSet rs = stmt.execute();
if(rs.next()){
// I don't know what your query returns
//I'll assume you use only the first result , it'll be an int
result = rs.getInt(1);
}
stmt.close();
// Now you decide what to do with result.
HTH,
WB::

Related

SQL connection busy although it's already closed

My SQL connection keeps saying it's busy even though all previous connections are closed.
The error below results. All others are either closed by the exiting of the JFrame or the .close() method. Does anyone see anything wrong with the class? (All other classes work as intended.)
SEVERE: null
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.execute(DB.java:854)
at org.sqlite.core.DB.executeUpdate(DB.java:895)
package teacherreviewproject;
//initialise imports
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class FeedbackForm extends javax.swing.JFrame {
//init. variables
String WWW;
String EBI;
int rating;
String teacher;
String studentUser;
String ratingraw;
String teacherQuery;
public FeedbackForm(String s) {
initComponents();
getTeachersNames();
this.studentUser = s;
}
private void getTeachersNames(){
//get the connection
Connection con = DBConnection.getConnection();
//set up query string
this.teacherQuery = "SELECT * FROM users WHERE type=2";
try {
//prepare statement
PreparedStatement teacherState = con.prepareStatement(teacherQuery);
//execute query
ResultSet teachResult = teacherState.executeQuery();
//clear previous items to avoid duplicates.
jComboBox_teachers.removeAllItems();
//create counter variable to get different teachers in RS
int i = 0;
//while loop
while(teachResult.next()){
//get username then add it to position i at combobox
String tempOption = teachResult.getString("username");
System.out.println(tempOption);
jComboBox_teachers.addItem(tempOption); //thanks mcalpine
//increment i
i++;
}
} catch (SQLException ex) {
Logger.getLogger(FeedbackForm.class.getName()).log(Level.SEVERE, null, ex);
}
Found the bug! I needed to make a close-if feature on my Connection class.
Here's the code, should anyone want it:
public class DBConnection{
public static Connection con = null;
public static Connection getConnection(){
//initialise connection
try{
//creates valid url to access DB with
String url = "jdbc:sqlite:" + System.getProperty("user.dir") + "/TeacherReviewIA.DB";
if(con == null){
con = (Connection) DriverManager.getConnection(url);
}else{
con.close();
con = (Connection) DriverManager.getConnection(url);
}
//as a debug measure and to show connection given
System.out.println(con);
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex,"WARNING",JOptionPane.WARNING_MESSAGE);
}
//allows code that called method to use connection given
return con;
}
}

Exhausted resultset java sqlexception

i've been getting the error exhausted resultset without really knowing what's wrong with what i'm doing, i'm basically trying to stock 3 rows from a database to an array of 3 elements of a class called "Logement" in my uni project which will be later used to fill a number of checkboxes in a javafx ui
package accesBD;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import metier.ConvIntToBool;
import metier.Logement;
public class LogementDAO {
TypeLogementDAO bd = new TypeLogementDAO();
public Logement[] findAll() throws SQLException {
Logement logements[] = null;
Connection cnx= SConnection.getInstance();
Logement logement = null;
try {
PreparedStatement st= cnx.prepareStatement("select* from logement");
ResultSet res= st.executeQuery();
int i =0;
while (res.next()) {
logement= new Logement(bd.find(res.getInt(1)), ConvIntToBool.boolToInt(res.getInt(2)) ,ConvIntToBool.boolToInt(res.getInt(3)),ConvIntToBool.boolToInt(res.getInt(4)),ConvIntToBool.boolToInt(res.getInt(5)),ConvIntToBool.boolToInt(res.getInt(6)));
//System.out.println(res.getRow());
logements[i]=logement;
i++;
}
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
return logements;//la collection retournĂ©e peut ĂȘtre vide
}
}
These are the 3 rows that i'm trying to receive from the database
and this is the code for the method find
public TypeLogement find(int id){
Connection cnx =SConnection.getInstance();
TypeLogement c=null;
try {PreparedStatement stp1=cnx.prepareStatement("select * from typelogement where id=?");
stp1.setInt(1, id);
ResultSet n= stp1.executeQuery();
while(n.next()){
c= new TypeLogement(n.getInt(1),n.getString(2),n.getDouble(3));
}
cnx.close();
} catch (SQLException e) {
e.printStackTrace();
}
return c;
}
Looks like the issue is because you close database connection:
You use Connection cnx= SConnection.getInstance(); to get connection in both findAll() and find(). And in find() you close connection. So the following happens:
You open connection in findAll()
You get outer ResultSet and iterate over it
In the loop you call find()
You call Connection cnx= SConnection.getInstance(); and get inner ResultSet
You close connection in find(). When you close connection it closes all result sets opened in that connection
Loop for outer ResultSet fails since result set was closed due to closed connection in find() method
Instead of closing connection you need to close ResultSet in find() method.

Java program fails with Oracle jdbc driver package doesn't exist in Ubuntu?

I have read a number of solutions posted here about this, but I can't seem to get the database connected for some reason. Here is my code first.
Note: The url, user and passwd have been deleted just for my privacy.
Also am I forgetting to import something in my java code?
import java.util.*;
import java.io.*;
import java.sql.*;
import java.util.Vector;
public class test
{
String createTableString = "create table dummy (count int)";
String insertIntoTableString = "insert into dummy values (2)";
String selectTableString = "select * from dummy";
String url="-----";
String user = "-----";
String passwd = "-----";
String result = "";
public test()
{
System.out.println("Accessing oracle database....");
} // end constructor
public void getResults()
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.err.println("Done with driver registrations!");
} catch(Exception e)
{
System.out.println("cant find the driver.");
}
try{
System.out.println("Trying to connect...");
Connection con=DriverManager.getConnection(url,user,passwd);
System.out.println("Connection successful");
Statement stmt = con.createStatement();
stmt.executeQuery(createTableString); // No need to return anything for creating table
stmt.executeQuery(insertIntoTableString);
insertIntoTableString = "insert into dummy values (20)";
stmt.executeQuery(insertIntoTableString);
insertIntoTableString = "insert into dummy values (2098)";
stmt.executeQuery(insertIntoTableString);
insertIntoTableString = "insert into dummy values (34)";
stmt.executeQuery(insertIntoTableString);
ResultSet rs = stmt.executeQuery(selectTableString); // returns table with metadata
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
result += rs.getString(1)+" ";
result += "\n";
}
System.out.println("\n"+result);
stmt.close();
con.close();
}catch(SQLException e){
System.out.println("SQLException: " + e);
}
}
public static void main(String args[]){
test obj = new test();
obj.getResults();
}
}
I am using Ubuntu 16.04 LTS, and I have only installed java just now, so I don't know if I have to install something else.
I tried compiling it using javac test.java but if fails with an error saying
test.java:25: error: package oracle.jdbc.driver does not exist
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
^
1 error
Like someone said on another SO question, i tried compiling it using javac -classpath ".;/home/path-till-jar/ojdbc14-10.2.0.3.0.jar;" test.java but it fails with the same error as above. The ojdbc14-10.2.0.3.0.jar was a file that I got from some site. I don't know if that's the right jar as it was extremely difficult to figure out which jar file to download since there is no good source online.

How to use #queryparam when using array in Java

I am using a restful web service and I was able to display database records using an array. But I am confused on how will I be able to display my desired record. I have here the class where the SQL query is being executed. I am using Advanced Rest Client google chrome application in testing the response and the output. How will I be able to query 'select * from taxi where taxi_plate_no='inputted data''? I am really confused on how will I be able to do it in an array. Please help me. Thank you! :(
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.ws.rs.QueryParam;
import com.taxisafe.objects.Objects;
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
#QueryParam is annotation used in rest webservices .
And i think here you want to use parameter with your SQL query.
So using parameter in PreparedStatement use following code
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con,String taxiNumber) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi WHERE taxi_plate_no= ?");
stmt.addString(1,taxiNumber);
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
Note: Use parameter taxiNumber or any other parameter you want to
retrive data on that parameter
and use setString(position,value); to replace ? with that parameter

How do I call variables from a Java class into another Class?

I've read about inheritance or using the import. I just simply am unable to get the right answer. Firstly my code is of the following form:
class queries{
String query1="Select * from "+tableName+";
String query2="Select "+columnName+" from "+tableName+";
}
Now, I have another class where I wish to make make SQL queries using the queries mentioned in the queries class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class test{
public static void main(String args[])throws SQLException
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("This is Wrong");
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connect = DriverManager
.getConnection("SQLCONNECTION");
PreparedStatement preparedStatement = connect
.prepareStatement(THIS SHOULD CALL query1 or query2);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("THIS RUNS");
//display text
}
preparedStatement.close();
connect.close();
}
}
So well, I need to figure out how to call query1 or query2 from the queries class in test. Sorry, but I hope someone can help me how to do this in a clean way. I can also create a Hashtable in queries where I call the respective query based on its name.
Thanks a lot.
class queries
{
public static String getQuery1(String tableName)
{
return "Select * from "+tableName;
}
public static String getQuery2(String tableName, String columnName)
{
return "Select "+columnName+" from "+tableName;
}
}
Then do this:
PreparedStatement preparedStatement =
connect.prepareStatement(queries.getQuery1("INSERT TABLE NAME HERE"));

Categories