Generate Jar File - Java Netbeans with Mysql localhost - java

I have created a java application in netbeans, and I intend to create an installer for the project.
For this I have created a jar file of the application, but I'm using the mysql database localhost.
How can I generate Jar File with Mysql localhost .
Can anyone help me please?
Thanks and regards
-----------------------------Edit---------------------------------------
Maybe not the best way to express myself, what I mean is that the database is created locally (localhost).
The connection of the application with the database is done this way:
Class.forName("com.mysql.jdbc.Driver");
return driverManager.getConnection("jdbc:mysql://localhost/database","root", "root");
I want to create a jar file of my application that has a database created locally.

I am going to explain a few things:
You do not need to hard - code the Connect URL into your code. This is why you are asking for ways of creating the database as localhost. I suggest you do not hard code the Connect URL in the code. Instead write it in an editable File either a Properties file or even a text file. Let the Application read the Editable file and pass the Parameters to the Code.
An Application running in your Local Machine where the database is will connect using Localhost. But a the same Application running remotely from another Machine whether in the Internet or Local access network will not Connect this way.That is why I am insisting on NOT Hard-Coding the Connect String.
The database Name, user, and Password Including the Host will change from time to Time depending on which environment the Application is running in. So again if the environment changes and the variables are not the same the Application will Not Connect to the database.
Suggestion:
User a Properties file:
db.host=192.168.1.23
db.user=root
db.password=root
db.dbname=database
Load the file as a Properties file:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("db.host"));
System.out.println(prop.getProperty("db.user"));
System.out.println(prop.getProperty("db.password"));
System.out.println(prop.getProperty("db.dbname"));
//PASS YOUR CONNECT STRING
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("db.host") + "/" + prop.getProperty("db.dbname"), prop.getProperty("db.user"), prop.getProperty("db.password"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This way you will never have to worry about what database the application is running on as you will just have to edit the config.properties and the Application will do the rest.
I hope I gave you an answer or better still other ideas on how to handle your situation.

Related

Using Java to Connect to MySQL Connection from multiple computers

A few classmates and I are creating a Java project which requires a database. I have created a connection in MySQL and connected it to my Java project successfully using the following Connect class:
package com.example.javaworkoutgame.Model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect {
static Connection con;
public Connect() {
connect();
}
// attempt to connect to MySQL database
public static void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver Loaded Successfully");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lab3", "root",
"**********"); // not the actual password
System.out.println("Successful Connection");
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
This code runs properly on my machine.
I committed and pushed the code to Bitbucket so my partners could access it. However, when they run the code on their computers, they get the following error message:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
Is there something I need to change in MySQL workbench in order for other people to be able to access the database? I could not find any information on this.
The only thing I was able to try was found at this thread:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
I opened a new .sql file and tried running the command:
GRANT ALL PRIVILEGES ON . TO 'root'#'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;
(I replaced '%password%' with the actual password)
When I tried that I got the following error message:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY '*********' WITH GRANT OPTION'
No, and you need to stop this line of thought and do some research first.
Your current configuration says that the mysql server is on the very same physical machine that the code is running on. You installed mysql on your dev machine, your friends need to install it on theirs, and each has their own unique database (nothing is shared).
You could, instead, take your mysql server, open it up to the world (which, for virtually all ways internet is made available in residential connections, requires messing with your router to 'open a port').
But then you have an open mysql server, and the username and password are on a public bitbucket site.
It also requires either a permanent IP (which few residential internet providers offer) or a dyndns service. More generally, hosting open MySQL servers that see lots of traffic gets your internet shut down, for good reason. You'd end up hosting a whole bunch of hackers. All hardware in your network will be p0wned and turned into bot nets. Hence, very very bad idea.
Good ways to solve this problem:
Everybody installs their own MySQL server. This is sensible; you're writing code and bound to make mistakes, it'd be real bad if all code you write is first-run and tested on live data. You don't want one of your friends to wipe your database. If you need some initial data to test with, set it up properly, and read up on how to make an SQL dump. With such a dump file you can reset any mysql server to that exact state - and that'd be how you and your friends develop: Set up the DB to be in that known state, write some code, and if you ruin the db by doing so, no problem. Just reset it again.
Set up a VPN between your friends. NOW you can share the IP your system has within the VPN (it'll be 10., 172.16., 192.168.* - if it's 127.0.0.1, it's localhost, i.e. everybody needs to install mysql on their own and nothing is shared, and if it's anything else, you're opening it to the world, which you don't want to do). Do not put the VPN username/password info anywhere in that bitbucket. And you need to trust your friends.
You should have a properties type file so that each person who is going to interact with the code has their local data without the need to replicate yours, in the same way you can have different values ​​in the properties for test or production environments.
example of a property file:
system.properties
#BD
db.driver=com.mysql.cj.jdbc.Driver
db.user=user
db.pass=password
db.server=server_IP
db.port= port_IP
db.db = DB
Then you should have a procedure to read from java the properties inside the file
Utils.java
package com.example.javaworkoutgame.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public final class Utils {
public static Properties getProperties() {
String path = String.format("PATH to your properties FILE/system.properties",
System.getProperty("user.dir"));
Properties properties = new Properties();
try (InputStream is = new FileInputStream(new File(path))) {
properties.load(is);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return properties;
}
}
And finally you make a call to the function that gets the properties from your connection class
Connect.java
package com.example.javaworkoutgame.Model;
import com.example.javaworkoutgame.util.Utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect {
Properties properties = Utils.getProperties();
static Connection con;
public Connect() {
connect();
}
// attempt to connect to MySQL database
public static void connect() {
try {
String driver = properties.getProperty("db.driver");
String ip = properties.getProperty("db.ip");
String port = properties.getProperty("db.port");
String db = properties.getProperty("db.db");
String user = properties.getProperty("db.user");
String pass = properties.getProperty("db.pass"):
Class.forName(driver);
System.out.println("Driver Loaded Successfully");
con = DriverManager.getConnection("jdbc:mysql://"+ip+":"+port+"/"+db, user,
pass);
System.out.println("Successful Connection");
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
About the MYSQL error, if your partners do not have a local mysql environment with the same values ​​as you, they will experience the error you describe, since your configuration is a local configuration, if you need your partners to connect to your pc, you must open the ports of mysql and give them your public IP (not recommended)
I hope this answer helps you!

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Java: Connecting to a MySQL Database? DriverManager.getConnection()? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
So I was just wondering, what (and probably, how much...) have I done wrong here with this code?
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
As I've triple-checked the username/password, I'm guessing it's something wrong with the host name. The database is only on the server (I don't have any kind of saved local version or anything...do I need to?).
And also, can someone just tell me if I'm on the right lines for what I want to do? Basically I've created a piece of software with a free version and a very cheap paid version. I was thinking that to prevent piracy, since the program requires internet connection anyway, I could store their email address as the username, then their computer's MAC address would be the password (each time the program was run, I would compare the MAC address on their PC with the one registered along with their email in the database. I've got no idea whether that is a good anti-piracy measure, but I was just wondering, if I manage to get the connection working, is that something that I'd be able to do or would there be e.g. security issues with that?
Anyway, thanks in advance :)
if it is not localhost i cannot comment on the host but you also have to give port number.It is missing.
Connection con = DriverManager
.getConnection("jdbc:mysql://"+pHost+":"+pPort+"/Your_mysql_schema_name",username, password);
and also in MYSQL your schema name would be your database name.Ensure that you are giving schema name and also port number.Usually for MYSQL its 3306
Writing a piece of java code to operate your database from a remote connection is not a good idea. Someone could reverse engineer your code and change your data.
You should atleast Implement an simple service on the net that could handle the spam you might receive, and protect your data.
I Think you missed the database port no in your URL .Try this :
try {
Class.forName("com.mysql.jdbc.Driver"); // Not Required for JDBC 4.0 onwards
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com: 3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Try instead of mysql1.000webhost.com to change with server IP address.
Example,
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://123.456.789.012:3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
I would recommend you some reading first. This slide show might present you how Java EE applications are build.
Next you might want to read a bit more how to connect your application with a database.
Hibernate is one of the most widely used tools for establishing connection between database and your Java program. It allows you to separate your connection data (e.g. username, password, connection url) from your code with use of configuration files in xml format. The line:
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
Is a very dangerous way of establishing connetion, as you are providing confidential credentials inside the code. There are ways to retreive this information from binary files.
You also asked, if is it worth having some local version of your database. The anwser is: Yes. Having your database locally might significantly speed up the time required for development and testing. It also allows you to work on your code even when no internet connection is available.
Providing authentication with use of MAC address is a very dangerous idea. Those addresses are attached to given machines. In other words the user will be able to connect to your application only with machine, on which he or she created an account. When using other computer (e.g. laptop at work) authentication will be denied.

How to connect to mysql using eclipse running apache

I am creating a dynamic web project in eclipse. I have my local apache server running and configured with appropriate resource, mysql running and configured with the appropriate port.
I downloaded the appropriate driver, included it in the lib directory - I even tried adding it as an external JAR file to no avail. On the dynamic web page the result is "error connecting to database".
I created a JSP with the following code:
<%# page import="java.sql.*"%><%# page import="java.io.*"%><%# page import="com.mysql.*"%><?xml version="1.0"?>
<tours>
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jbdc:mysql://localhost:3306/tours", "root", "root");
out.println("connected to database!");
}
catch(SQLException e) {
out.print("error connecting to database");
}
%>
</tours>
Please advise...
Thanks in advance.
Put print after Class.forName() check, if that statement is not printing then problem is driver if that line is printing then problem is mysql database name problem or credential problem
If problem in drive then download from here :
http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
Problem is u put jbdc instead of jdbc
Code like this
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
out.println("Driver is available !");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tours",
"root", "root");
out.println("connected to database!");
}
catch(SQLException e) {
out.print("error connecting to database");
}
%>
There are couple of things to take care of here.
1. Make sure that mysql is listening on port 3306.
2. Cross check the database name.
Lastly get the driver jar file in deployment assembly.
If the problem still persists, please print the stacktrace and post it here.
Please check weather your database is started or not i know it should be in comment but i cannot keep it in comment because i don't have sufficient reputations. please try it if it helps you it is fine.
How to start database is shown below:
Click Windows button+r then enter Services.msc in search bar then select Mysql and click start option
Printing the stack trace might help it could be because of authorization issue. If the error is related to authorization issue, you may have to change the server configurations.

How can i check if MySQL and Tomcat are running?

I've created a Java application that is split in different subcomponents, each of those runs on a separate Tomcat instance. Also, some components use a MySQL db through Hibernate.
I'm now creating an administration console where it's reported the status of all my Tomcat instances and of MySQL. I don't need detailed information, but knowing if they are running or not it's enough.
What could be the best solution to do that?
Thanks
Most straightforward way would be to just connect the server and see if it succeeds.
MySQL:
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
// Succes!
} catch (SQLException e) {
// Fail!
} finally {
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
Tomcat:
try {
new URL(url).openConnection().connect();
// Succes!
} catch (IOException e) {
// Fail!
}
If you want a bit more specific status, e.g. checking if a certain DB table is available or a specific webapp resource is available, then you have to fire a more specific SELECT statement or HTTP request respectively.
I assume that you know the ports of which are running in advance (or from configuration files). The easiest way to check is to make socket connections to those ports like a telnet program does. Something like:
public boolean isServerUp(int port) {
boolean isUp = false;
try {
Socket socket = new Socket("127.0.0.1", port);
// Server is up
isUp = true;
socket.close();
}
catch (IOException e)
{
// Server is down
}
return isUp;
}
Usage:
isTomcatUp = isServerUp(8080);
isMysqlUp = isServerUp(3306);
However, I would say that is a false-negative check.. Sometimes it says server UP but the server is stuck or not responding...
I would make sure that what ever monitoring you setup is actually exercising some code. Monitoring the JVM via jmx can also be helpful after the fact. Check out http://www.cacti.net/ .
Firing a simple fixed query through MySQL
SELECT 'a-ok';
and have the .jsp return that a-ok text. If it times out and/or doesn't respond with a-ok, then something's hinky. If you need something more detailed, you can add extra checks, like requesting now() or something bigger, like SHOW INNODB STATUS.
The easiest thing is to look for the MySQL and Tomcat PID files. You need to look at your start scripts to make sure of the exact location, but once you find it, you simply test for existence of the pid file.
Create a servlet as a status page. In the servlet perform a cheap query, if the query succeeds let the servlet print OK otherwise Error. Put the servlet into a war and deploy it to all instances.
This could be used for checks in yor admin console by doing a loop over all instances.
I'd create a simple REST webservice that runs on each Tomcat instance and does a no-op query against the database. That makes it easy to drive from anywhere (command line, web app, GUI app, etc.)
If these are publicly available servers you can use a service like binarycanary.com to poll a page or service in your app.

Categories