Here is my application's code to create the database, connect to it, and make a table in the database called Accounts.
package eportfolio.application;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* #author valeriomacpro
*/
public class HomePage extends javax.swing.JFrame {
public static String username;
public static String password;
public static int SelectedPost;
/**
* Creates new form HomePage
*/
public static boolean doesTableExists (String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public HomePage() {
initComponents();
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
} catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
}
Additionally, here is my code that interacts with the Accounts table.
try
{
String databaseURL = "jdbc:derby:eportdatabase;";
Connection con1 = DriverManager.getConnection(databaseURL);
Statement st = con1.createStatement();
String sql = " INSERT INTO Accounts VALUES ('"+txtNewUsername.getText()+"','"+txtNewPassword.getText()+"') ";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Account Info Saved!");
txtNewUsername.setText("");
txtNewPassword.setText("");
txtNewConfirm.setText("");
}
When I run the application, the code works fine. However, if I open DBeaver and connect it to my database, then the following error message comes up. Does not come up if DBeaver is closed, even if it is connected to the database.
Message:Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XJ040: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
SQLState:XSDB6
Error Code:45000
Message:Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Why is this? Am I connecting the Database to DBeaver incorrectly? Or am I coding the database incorrectly in Netbeans? It could be that my drivers and db derby version are old, but I have not been able to find help on that online either. Also important to know that the table does show up in DBeaver, but does not update. I have to delete the database folder in my application's folder every time I want to use the application with DBeaver open. Any help appreciated.
By using this line of code:
String databaseURL = "jdbc:derby:eportdatabase;";
you are using Derby in the "embedded" configuration. With Embedded Derby, only one Java application at a time can use the database. Other applications that try to use it concurrently are rejected with the message
Another instance of Derby may have already booted the database
as you saw when you tried it.
There are other configurations in which Derby can be deployed and run; specifically there is a Client-Server configuration in which multiple applications may all run as clients, and may connect to the same Derby server, allowing the applications to run concurrently.
To learn more about these aspects of Derby, start here: https://db.apache.org/derby/docs/10.15/getstart/cgsquck70629.html
Related
Please start by knowing I am a total beginner. The code that will be posted below is from "YouTube".
The code is to establish a connection to Mysql workbench database "mysql".
Purpose is to create a table with column names.
The project runs fine. Well! No visible hick-ups. The output window in Netbeans reads:
run:
Connected
Function complete.
BUILD SUCCESSFUL (total time: 1 second)
Can't negotiate MySQL Workbench documentation to possible reasons for not listed the Table. But still looking.
I replaced part of the "CREATE TABLE IF NOT EXISTS..." with "CREATE TABLE..."
The output window in Netbeans then reads:
run:
Connected
java.sql.SQLSyntaxErrorException: Table 'actors'
already exists
Function complete.
BUILD SUCCESSFUL (total time: 1 second)
package homemovies;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class HomeMovies {
public static void main(String[] args) throws
Exception { creatTable(); }
public static void creatTable() throws Exception{
try{
Connection con = getConnection();
PreparedStatement create =
con.prepareStatement("CREATE TABLE IF NOT EXISTS
Actors(id int NOT NULL AUTO_INCREMENT, "
+ "Fname varchar(255), Lname
varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{System.out.println("Function
complete.");}
}
public static Connection getConnection() throws
Exception{
try{
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mysql";
String username = "username here";
String password = "password here";
Class.forName(driver);
Connection conn =
DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
}
Expect the table "Actors" to be listed in Tables section of MySQL Workbench.
I tried additional things like stopping the server, closing MySQL Workbench application; Restarting the application and the server. The Table "Actors" still continues not to show up where it should.
Please help.
Appreciate your time.
Thank you.
IF NOT EXISTS prevents error from occuring. You can check the manual here https://dev.mysql.com/doc/refman/8.0/en/create-table.html
If you try to run the query multiple times without IF NOT EXISTS in MySQL workbench, you would get a similar error.
I have used in the past few months XAMPP with MySQL database(s), which were created and modified with phpMyAdmin on localhost, for my university JavaEE projects. The MySQL database and Apache server are started from the XAMPP Control Panel. Everything went fine.
Now I am developing my own Java Desktop Application using JavaFX/Scene Builder/FXML and I want to use a database to store and load various information processed by the Java Application through JDBC.
The question is, how to start the MySQL database on localhost, without using the XAMPP Control Panel manually, when I finish my Java Application and deploy it as stand alone program and start it just from a single shortcut?
Any way to make the shortcut of the program also start the MySQL database on my PC before/while it starts the Java Application? Or maybe there is a way to do that inside the Java code? Or maybe some other way, that is not known to me?
I am not strictly determined on using only the XAMPP/MySQL/phpMyAdmin setup, it is just already all installed on my PC and I know how to work with it, thus the easiest solution so far. So if there is some better way/database setup for home/small applications, please feel free to suggest some :). I am not sure at all if what I want to do is possible with the XAMPP setup.
Side note: I persist on using localhost DB instead of Serialisation/Deserialisation with Java, because I want the Application to be independent of internet connection and yet have the opportunity to have a ready DB to be transferred to an online DB, if such I decide to do it in the future.
On the root of the Xampp folder you have one mysql_start.bat and one mysql_stop.bat, for start/stop the mysql database included on the Xampp package.
You can use they in another bat you should create to start your Java Desktop application.
ProcessBuilder P1 =new ProcessBuilder("C:\\xampp\\mysql_start.bat");
P1.start();
ProcessBuilder P2 =new ProcessBuilder("C:\\xampp\\APACHE_start.bat");
P2.start();
You can do it like this -
To connect to the Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Statement statement;
//function to connect to the xampp server
public void DatabaseConnect(){
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/javafx","root","");
/*here javafx is the name of the database and root is the username of
your xampp server and the field which is blank is for password.
Because I haven't set the password. I have left it blank*/
statement = conn.createStatement();
System.out.print("Database Connected");
} catch (Exception e) {
System.out.print("Database Not Connected");
}
}
Below given are the various operations you can perform after connecting to the database.
//for inserting data
public void insert(){
try{
String insertquery = "INSERT INTO `tablename`(`field1`, `field2`) VALUES ('value1', 'value2'";
statement.executeUpdate(insertquery);
System.out.print("Inserted");
} catch(Exception e){
System.out.print("Not Inserted");
}
}
//for viewing data
public void view(){
try {
String insertquery = "select * from `table_name` where field = 'value1'";
ResultSet result = statement.executeQuery(insertquery);
if(result.next()){
System.out.println("Value " + result.getString(2));
System.out.println("Value " + result.getString(3));
}
} catch (SQLException ex) {
System.out.println("Problem To Show Data");
}
}
//to update data
public void update(){
try {
String insertquery = "UPDATE `table_name` set `field`='value',`field2`='value2' WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Updated")
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
//to delete data
public void delete(){
try {
String insertquery = "DELETE FROM `table_name` WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Deleted");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
Also, don't forget to add the JAR file in your system library. For this example, I have used mysql-connector-java-5.1.46
In the example below showing how to use Java's SQL library, Class.forName() is called without a variable to save a reference to the object. What is the purpose of doing this if you cannot manipulate it later? I've seen that line written in various examples of the SQL library.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
It makes the class initializer run - which in the case of JDBC drivers used to be the way that the driver would register itself with DriverManager. In modern Java, JDBC drivers are usually found using the service provider API.
From the docs:
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
OK so I made a mysql database on godaddy.com
I made an admin table there with 3 fields, ID,Username and Password.
In my program I connected to the database and it shows me the tables so I know its connected(Netbeans)
I downloaded Java JDBC driver and put it in the library of my project.
However when I run the program I get this error:
package testdata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestData {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String Name = "rsg";
String Pass= "dfgd";
String Host = "blahhhhhhhhhhhhhhh";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="DELETE FROM ADMIN";
stmt.executeUpdate(query);
String sql = "SELECT * FROM ADMIN";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
rs.updateInt("ID", 1 );
rs.updateString("Username", "CHRIS");
rs.updateString("Password", "CHRIS");
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
error is:
java.sql.SQLException: No suitable driver found for ****THIS IS MY HostName****
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at testdata.TestData.main(TestData.java:28)
add mysql conntector jar file in your classpath.
I thing it's an issue with your host address. Check how should it look in MySql documentation
use
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DatabaseUrl, DataDaseusername, DatabasePass);
example for DatabaseUrl is given below
jdbc:mysql://192.168.100.100/databasename
mysql-connector-java-5.1.22 download from mysql.com
Insure you have add the jar folder in your project.
I believe its is looking for com.mysql.jdbc.Driver
make sure your connection string is correct for an example "jdbc:mysql://remot-example-mysql999.servage.net:3306/databasename?zeroDateTimeBehavior=convertToNull";
Your JDBC connection string is not correct (you cannot simply use the hostname). You need to use a JDBC URL, which for MySQL takes the form:
"jdbc:mysql://<hostname>:<port>/<database>"
Where <port> is optional if your server is running on the default, and is also optional. Change your getConnection method to this:
connection = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "3306", "YourDBName"),
Name, Pass);
Replace "YourDBName" with the name of the database you are trying to connect to. You also need to have the MySQL driver JAR in your classpath.
well I have a pretty awkward situation. I have a working database managers class, which works when I run it on the desktop version of it (Swing GUI), however, when I run the same class on the servlet, I get a strange error, that it can't get the connection. I am using database pooling for optimisation.
So the error looks as follows:
Error in Database Connection: Error getting connection to database - java.sql.SQLException: No suitable driver found for jdbc:sqlserver://isd.ktu.lt:1433;DatabaseName=LN2012_bakDB2
And the class with the methods involved looks like this:
package Core;
import DataTypes.Parameters;
import Interfaces.OutputInterface;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
*
* #author arturas
*/
public class DatabaseConnection {
String specificError = "Error in Database Connection: ";
OutputInterface gui = null;
boolean allowOutput = true;
GenericObjectPool connectionPool;
ConnectionFactory connectionFactory;
PoolableConnectionFactory poolableConnectionFactory;
PoolingDriver driver;
Connection con = null;
public DatabaseConnection(Parameters params) {
// parameters and the output
this.gui = params.getGui();
// activate database pool
connectionPool = new GenericObjectPool(null);
connectionFactory = new DriverManagerConnectionFactory(params.getDbAdr(), params.getDbUser(), params.getDbPass());
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
driver = new PoolingDriver();
driver.registerPool("GenTreeDatabase", connectionPool);
}
public void openConn() {
if (allowOutput) gui.print("Getting connection to database");
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:GenTreeDatabase");
if (con != null) {
if (allowOutput) gui.print("Connection to database was successful");
}
} catch (SQLException ex) {
gui.err(specificError + "Error getting connection to database - " + ex);
}
}
public void closeConn() {
try {
con.close();
if (allowOutput) {
gui.print("Connection to database closed successfully");
}
} catch (SQLException ex) {
gui.err(specificError + ex);
}
}
The error appears when the try in method openConn is called.
Can anybody help me with this?
You are getting this error because there is no drivers in your classpath. Probably in your desktop application there were. You need to put driver's .jar file into your servlet container's global classpath or in your application classpath and it should work.
I prefer adding driver's jar into server global classpath, because there can be more than one application which will use the same .jar file to load drivers.
make sure of this
1) you should make sure that .jar library is compatabile with RDMS you are using
2) that you included the .jar for connection in your netbeans in
projectproperties-->libraries
3)copy the .jar into C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.26\lib
and this is important
if you dont have the driver in location you get not found error but
you get no suitable so i think the version must be incompatible so what version of sql server are you using...