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;
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
package persistentie;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domein.Speler;
public class SpelerMapper {
private List<Speler> spelers = new ArrayList<>();
private List<Integer> scoreSpeler = new ArrayList<>();
private static final String UPDATE_SCORE = "insert into ID343589_g52.scoreSpeler(spelerNr,score) values(?,?)";
public SpelerMapper() {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement("SELECT * FROM ID343589_g52.speler");
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
String gebruikersnaam = rs.getString("gebruikersNaam");
String wachtwoord = rs.getString("wachtwoord");
spelers.add(new Speler(gebruikersnaam, wachtwoord));
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public boolean correcteGegevens(Speler nieuweSpeler) {
return spelers.contains(nieuweSpeler);
}
public List<Integer> geefscoreSpeler(String naam) {
scoreSpeler.clear();
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
int score = rs.getInt("score");
scoreSpeler.add(score);
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return scoreSpeler;
}
public void slaScoreOp(int score, String naam) {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
int id = 0;
while (rs.next()) {
id = rs.getInt("score");
}
PreparedStatement update = conn.prepareStatement(UPDATE_SCORE);
update.setInt(1, id);
update.setInt(2, score);
update.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
anything stupid I am doing here that is realy not how it working? I am really new to connecting a database with my java projects? the thing that I am trying to do in methode geefScoreSpeler() is getting the scores of an idividual player. and in methode slaScoreOp() I am trying to insert a new column in a table (also trying to get the id of the username via a table that innerjoins)
Hey there I made a user management system and this is my DAO(Databases connection class)
I have used prepared statement in this to see if it might help.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import com.ums.beans.ems.Employee;
public class EmployeeDao {
Connection connection;
Statement statement;
public EmployeeDao() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_1", "root", "apaar121");
}
public int saveEmployee(Employee employee) throws SQLException {
String query = "INSERT INTO user_1.employee ('name','dob','address','phone','email','education','designation','salary')VALUES (?,?,?,?,?,?,?,?);";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,employee.getName());
preparedStatement.setString(2,employee.getAddress());
preparedStatement.setString(3,employee.getDesignation());
preparedStatement.setString(4,employee.getDob());
preparedStatement.setString(5,employee.getEducation());
preparedStatement.setString(6,employee.getEmail());
preparedStatement.setString(7,employee.getPhone());
preparedStatement.setFloat(8,employee.getSalary());
return preparedStatement.executeUpdate();
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I was trying to read a text file & load into SQL Server DB but when I run the following code, I am getting Array out of bound exception.
Can one guide, how can I fix this issue?
package com.companyname.product;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoadTextFileintoDB
{
public static void main(String[] args)
{
DBase db = new DBase();
Connection conn = db.connect(
"jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databaseName=ODRDev","sa","Abc-1234");
db.importData(conn,args[0]);
}
}
class DBase
{
public DBase()
{
}
public Connection connect(String db_connect_str,
String db_userid, String db_password)
{
Connection conn;
try
{
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection(db_connect_str,
db_userid, db_password);
}
catch(Exception e)
{
e.printStackTrace();
conn = null;
}
return conn;
}
public void importData(Connection conn,String filename)
{
Statement stmt;
String query;
try
{
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
query = "LOAD FROM 'C:/Investedge/JH765IDG_1.txt INTO TABLE InvestedgeDaily (AccountNumber,Code,Date,value);";
stmt.executeUpdate(query);
}
catch(Exception e)
{
e.printStackTrace();
stmt = null;
}
}
};
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at
com.companyname.product.LoadTextFileintoDB.main(LoadTextFileintoDB.java:15)
This Code triggers the exception:
args[0]
Obviously, no parameters were passed to the executable when executing it.
args is an array of the parameters passed to the executable in the command line.
I have one method which get connection from database. I run profiler using visualvm. I found out that the very first time I called method which is to get connection from databse takes longer than the rest.
How to avoid getting database connection multiple times?
It's doesn't matter with java servlet or java program or application server, it is just a design idea.
Here is a simple demo, i use MySQL ,hope to explain this design idea:
Class MyConnection:
package mysql;
import java.sql.Connection;
public class MyConnection {
private Connection connection;
private boolean isUsed;
public void setConnection(Connection connection) {
this.connection = connection;
}
public void setUsed(boolean isUsed) {
this.isUsed = isUsed;
}
public Connection getConnection() {
return connection;
}
public boolean isUsed() {
return isUsed;
}
}
Class MyConnectionPool:
package mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MyConnectionPool {
//this pool will hold the connection
static List<MyConnection> connectionPool = new ArrayList<>();
public MyConnectionPool() {
String mysqlConfigString = "jdbc:mysql://IP:3306/dbname?user=username&password=password";
int size = 0;
while (size++ < 10) {
Connection conn;
try {
conn = DriverManager.getConnection(mysqlConfigString);
MyConnection myConnection = new MyConnection();
myConnection.setConnection(conn);
myConnection.setUsed(false);
connectionPool.add(myConnection);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public MyConnection getConnection(){
for (MyConnection myConnection : connectionPool) {
if(myConnection.isUsed()){
System.out.println("connection is used");
continue;
}
myConnection.setUsed(true);
return myConnection;
}
return null;
}
}
Class test:
package mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MysqlTest {
public static void main(String[] args) throws SQLException {
MyConnectionPool pool = new MyConnectionPool();
// connection one
MyConnection myConnection = pool.getConnection();
Connection conn = myConnection.getConnection();
PreparedStatement ps = conn.prepareStatement("select count(*) as co from asset");
ResultSet rs = ps.executeQuery();
rs.next();
System.out.println(rs.getString("co"));
ps.close();
// connection tow
myConnection = pool.getConnection();
conn = myConnection.getConnection();
ps = conn.prepareStatement("select count(*) as co from asset");
rs = ps.executeQuery();
rs.next();
System.out.println(rs.getString("co"));
// connection three
myConnection = pool.getConnection();
conn = myConnection.getConnection();
ps = conn.prepareStatement("select count(*) as co from asset");
rs = ps.executeQuery();
rs.next();
System.out.println(rs.getString("co"));
//reset connection use status
myConnection.setUsed(false);
// re-use connection three
myConnection = pool.getConnection();
conn = myConnection.getConnection();
ps = conn.prepareStatement("select count(*) as co from asset");
rs = ps.executeQuery();
rs.next();
System.out.println(rs.getString("co"));
}
}
Because i never close the connection in MyConnectionPool, so i can re-use the connection.
It is very simple demo. Real Connection Pool is very Complex.
You can find some Connection Pool jar.
I don't know what ORM framework you choose, the popular ORM framework all support Database Connection Pool.
i don't understand why my variable state cannot be resolved.
i'm in a java Mysql project.
Here is the Commands class code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Commands {
public Commands() throws SQLException{
Connection conn = DbConn.getInstance();
Statement state = conn.createStatement();
}
public String getList(){
System.out.println("Here is a List of our Products:");
// Get list from db
ResultSet result = state.executeQuery("SELECT * FROM products");
ResultSetMetaData resultMeta = result.getMetaData();
// Display the List
System.out.println("List displayed");
return null;
}
}
Here is the DbConn class code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConn {
private static String url = "jdbc:mysql://localhost:3306/myDB";
private static String user = "root";
private static String passwd = "";
private static Connection connect;
// create new instance if not exists
public static Connection getInstance(){
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connect;
}
}
My code is not finished yet, but the message come on this line:
ResultSet result = state.executeQuery("SELECT * FROM products");
My Eclipse editor says this message state cannot be resolved
Any idea?
That is a matter of scope. You define the variable here
public Commands() throws SQLException{
Connection conn = DbConn.getInstance();
Statement state = conn.createStatement();
}
And that is the only place the variable is visible - in the constructor. Define it in the class and initialize it in the constructor:
private Connection conn = null;
private Statement state = null;
public Commands() throws SQLException{
conn = DbConn.getInstance();
state = conn.createStatement();
}
Declare "State" outside of that constructor.
Connection conn = null;
Statement state = null;
public Commands() throws SQLException{
conn = DbConn.getInstance();
state = conn.createStatement();
}
For an Oracle database, the following program will throw SQL exceptions only for some threads. Why downgrading resultSetConcurrency from CONCUR_UPDATABLE to CONCUR_READ_ONLY? In a single thread environment this is not happening.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main extends Thread {
public static final String DBURL = "jdbc:oracle:thin:#localhost:1521:DB";
public static final String DBUSER = "USER";
public static final String DBPASS = "PASS";
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0; i<20; i++)
new Main().start();
}
#Override
public void run() {
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
con.setAutoCommit(false);
try(PreparedStatement pstmt = con.prepareStatement("SELECT COLUMN1 FROM TABLE1 FOR UPDATE NOWAIT",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE))
{
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.updateString(1, "12345");
rs.updateRow();
}
}
finally
{
con.commit();
con.close();
}
}
catch(SQLException e)
{
if(!e.toString().contains("NOWAIT"))
e.printStackTrace();
}
}
}
You can look at the warnings raised against the result set/statement/connection to see why it was downgraded. With this added after the executeQuery() call:
SQLWarning warning = pstmt.getWarnings();
while (warning != null)
{
System.out.println("Warning: " + warning.getSQLState()
+ ": " + warning.getErrorCode());
System.out.println(warning.getMessage());
warning = warning.getNextWarning();
}
In this case you'll sometimes see:
Warning: 99999: 17091
Warning: Unable to create resultset at the requested type and/or concurrency level: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired
You're looking for a NOWAIT exception, but you're getting a warning. What isn't clear to me is why you still get a result set in that scenario; but you can at least trap that warning and not go into the result set loop if you see it.