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
Related
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
I am currently working on a project where we have to connect to a database and through Java insert values into our database. Our professor gave us code in order to help us see how to carry that out. I am new to Java and have very little experience in it but I have been watching videos and researching online. My problem is the following: I am working in eclipse and have created a class called _DataGenerator_ all the code that is there is from my professor.
import java.sql.*;
import oracle.jdbc.driver.*;
public class TestDataGenerator {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String database = "jdbc:oracle:thin:#131.130.122.4:1521:lab";
String user = "a+MatrNr";
String pass = "Oracle-Passwort";
// establish connection to database
Connection con = DriverManager.getConnection(database, user, pass);
Statement stmt = con.createStatement();
// insert a single dataset into the database
try {
String insertSql = "INSERT INTO person VALUES ('012345678902', 'Erich', 'Schiküta', 'Wien', 1010, 'Rathausstrasse 19', '12-FEB-2000', 'Wien')";
stmt.executeUpdate(insertSql);
} catch (Exception e) {
System.err.println("Fehler beim Einfuegen des Datensatzes: " + e.getMessage());
}
// check number of datasets in person table
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM person");
if (rs.next()) {
int count = rs.getInt(1);
System.out.println("Number of datasets: " + count);
}
// clean up connections
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
The only error I get when trying to run the code is from
import oracle.jdbc.driver.*;
When I put my cursor over the error symbol it says
the import oracle.jdbc cannot be resolved
When I try to run the code the only message I get back is
the statement in Red oracle.jdbc.driver.OracleDriver
I don't know what the problem is. I don't know if it helps to know that I have created my database in oracle SQL developer.
In eclipse, right click your project->Build Path->Config Build Path->find the Libraries tab and press the Add External Jars, locate your oracle jdbc driver in your hard driver and select it. Make sure it appears in the jars list, and then press apply and close.
you can find the oracle jdbc driver in the offical website:
https://www.oracle.com/technetwork/database/application-development/jdbc/downloads/index.html.
After that this issue should disappear.
Well,the jdbc lib of official oracle is not in maven repo,you should download it from Oracle Website and maven install your path.And if you use maven build your project,you can do this:
mvn install:install-file -Dfile=E:/app/Administrator/product/11.2.0/dbhome_1/jdbc/lib/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
Then add to dependency like :
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
I am new to this forum....
Iam tring to connect java project created in eclipse with oracle database xe,
I followed the procedures as descrided in the following link
https://www.youtube.com/watch?v=fMp63HsIRbc
but it didnt print the result in the eclipse console but it also didnt throw the exception as well
what should be the reason
this is my code
package dbmsoracle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdb {
public static void main(String[] args) {
System.out.println("jen");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
Statement st = con.createStatement();
String sql="select * from muhil";
ResultSet rs =st.executeQuery(sql);
while (rs.next())
{
System.out.println("executing ...");
System.out.println(rs.getInt(1)+" "+rs.getInt(2));
System.out.println("executed");
con.close();
}
}
catch (Exception e)
{
System.out.println("connection failed");
System.out.println(e);
}
}
i have downloaded my jdbc driver
Oracle Database 11g Release 2 (11.2.0.4) JDBC Drivers
ojdbc6.jar
Certified with JDK 8, JDK 7 and JDK 6: ......
and iam using jdk 8
Firstly check that your connection is establishing with oracle database or not. Here is the connection code try this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I have the same problem. The problem is your code doesn't catch(SQLException e). Because just catch(Exception e) will not make the exception of sql shown in the console. After doing this, you will probably find the Exception is "No suitable driver found for jdbc".
Then, either you can download the mysql-connector-java and add it to your lib, or if your project is Maven, you can just add dependency in your pom file.
After you used Sql+ for entering database, commit the table. Enter 'commit'(without quotes) on the terminal or either close your Sql+ terminal. In your case, you must have closed the terminal after you changed your id from 24, 253 to 1, 2. That is why it ran properly. Got nothing to do with id starting from 1
first of all go and check if your table has any data or not. It seems you just created this table 'muhil' before writing the above code. i'm pretty sure You must have entered some data as well in your new table. Just make sure you have Committed your transaction in the MYSQL Workbench. Just commit it and try to run your code in eclipse again.
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...
I am trying to connect my java program to a database that i have created using phpmyadmin using a university server. so the database is on the university server. how do i get the connection to the db from the java program? i have tried this code, but it gives me an error message?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Connector {
Connection con;
PreparedStatement stmt;
ResultSet rs;
Connector()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("https://NAMEHIDDEN.soi.city.ac.uk:5454/~kdhy546","root","");
stmt=con.prepareStatement("select * from staff where username=? and password=?");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I am not too sure even, whether this is the correct url to the database? how do i determine the exact link to the database in phpmyadmin?
phpMyAdmin in not a DBMS, it's an UI. If it's a MySQL database, you must use the MySQL JDBC
I have never used phpMyAdmin, but according to this tutorial you should get the connection string if you navigate to the MySQL Account Maintenance Section.
Another thing I am noticing is that you are missing your password in your connection, so without a password your application will not be able to connect.
Lastly, whenever you post a question on SO regarding some code which yields an error, please make sure you include the error, it helps us help you :).
Use the following code.
This is the java part:
import java.net.*;
public class mc
{
public static void main(String args[])
{
try
{
String username="ankur",password="ankur",fname="Shubhendu",ip="12345",lname="Goswami";
String up= "username=" + username + "&password=" + password + "&fname=" + fname + "&lname=" + lname + "&ip="+ ip;
URL url=new URL("http://127.0.0.1:80/alias1/index.php?"+up);
URLConnection urlc=url.openConnection();
urlc.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String str;
while((str=br.readLine())!=null)
{
System.out.print(str);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
PHP part: Anything you will echo from PHP will be stored in String str in Java code:
<?php
mysql_connect("localhost","root","")or die("unable to connect to server");
mysql_select_db("db_name") or die("Unable to connect to database");
$username=$_GET['username'];
$password=md5($_GET['password']);
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$ip=$_GET['ip'];
if(isset($username) && isset($password) && isset($fname) && isset($lname) && isset($ip))
{
$query="INSERT INTO tablename values('$username','$password','$fname','$lname','$ip')";
$fire=mysql_query($query);
}
?>
Hope it works.
Your URL to the database you created with phpMyAdmin is wrong. It should look something similar to:
jdbc:oracle:thin:#//myhost:1521/orc
I recommend you to have a web search for some good Java tutorials on this subject. :)