How to start a Mysql server in Java programatically? - java

My Java application needs to connect to a Mysql database file which is present on disk.
For that, it needs to start a Mysql server and use the server to read the file. The problem is that I am not sure how to start the server from within my Java code, read the Mysql file, make modifications to it, and then stop the server.
Currently, I am using something like below, but I don't see a way to start the server from code.
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setServerName("MysqlServer");
Connection conn = dataSource.getConnection();
Using this, I run into
Exception in thread "main" java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
which I think is because the server is not up. How do I start the server from code?

Option 1 : Find out how to start mysql from command line. Then use ProcessBuilder to do that
Option 2: Use embeddable version of mysql
, if that suits you : See details

you need to run 'mysqld.exe' to start the mysql server. This file can be found in the 'bin' folder in the mysql main folder (Assuming that you are working in windows). In my case 'mysql-5.6.10-win32\bin\mysqld.exe' .
From Java if you want to do the same - I used the following code and it worked. Hope it helps.
======================================================
String command = "~path~\\mysql-5.6.10-win32\\bin\\mysqld.exe";
try
{
Process process = Runtime.getRuntime().exec(command);
}
catch (IOException e)
{
e.printStackTrace();
}

Look into Runtime.exec(), which will allow you to start mySQL via console.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html

Runtime runTime = Runtime.getRuntime();
Process p = runTime.exec(String[] cmdarray, String[] envp, File dir);
p.waitFor();

Easiest way is to use JDBC all you need to do then is send queries to the server and interpret the results. A simple way to connect is below.
import java.sql.*;
Connection conn;
private void connect()
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://serverURL","user","pass);
System.out.println("Connection Established");
}
catch (Exception ex)
{
System.err.println("Unable to load the MySQL driver.");
ex.printStackTrace();
}

Related

Connection to derby database refused

I am learning Java and trying to put together a simple App containing a few jTables connected to database that can be updated etc. To do this I have created a database with a few tables through Netbeans which I understand (and wish) to be embedded in the final distributable app.
I am following the Programming Knowledge tutorials on Youtube to create most of the GUI. Everting is OK as long as I open the Services tab on Netbeans and manually right-click my database(testDB) and click Start Server. Then when I run the following code I get a successful connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
//Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Open a connection
String DB_URL = "jdbc:derby://localhost:1527/testDB";
String u_name = jTextField1.getText();
String p_word = jPasswordField1.getText();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/testDB",u_name,p_word);
JOptionPane.showMessageDialog(null,"Details Correct - Connection established");
Close_me();
Open_Table_GUI(u_name,p_word);
}
catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
However if I run that code WITHOUT manually clicking on start server I get the following:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused.
I have read the apache documentation and due to my level of inexperience I am not getting anywhere.
I have also checked out the answers to similar connection questions on here but again I can't seem to relate the issue in a way that works.
The ultimate goal for me is to have an app I can distribute to run on windows machines that will have the database/tables all included individually editable etc. I would hope to eventually create a database that resides on a shared drive and each individual can connect to automatically - but that's way down the line for now.
My request here is that someone can help me understand what I need to change in my code so that the "Start Server" is automatically done.
Thanks in advance for nay response.
OK guys so I found code that seems to work for me from a question asked on here by LMS
private void setup(){
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection=DriverManager.getConnection("jdbc:derby:sheet;create=true","test","1234");
statement=connection.createStatement();
}
catch(ClassNotFoundException cnf){
System.out.println("class error");
}
catch(SQLException se){
System.out.println(se);
}
}
If anyone cares to link me to a reason why this in fact works that would be great, I'm assuming the Embedded driver doesn't go through the port and just looks within the project??
Anyway initially this seems to be solved!!
Please check your Server setting i.e.
-username and pwd in your program
and check that did you start the Derby server and is it listening at port 1527?

Java won't connect to my database

Here's my code:
import java.sql.*;
public class DBConnector {
private static Connection conn;
public static void connectToDB()
{
//load the driver
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("Driver successfully loaded");
}
catch (ClassNotFoundException c)
{
System.out.println ("Unable to load database driver");
}
//connect to the database
try
{
String filename = "TopYouTubeVideos.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database += filename.trim () + ";DriverID=22;READONLY=true}";
conn = DriverManager.getConnection (database, "", "");
System.out.println ("Connection database successfully established");
}
catch (Exception e)
{
System.out.println ("Unable to connect to the database");
}
}
The output is:
Driver successfully loaded
Unable to connect to the database
This has worked on a different computer than mine, connecting to the database through exactly the same code... does anyone have any idea why?
Thanks in advance :)
EDIT: I'm running Access 2007, Windows 7 64bit
By checking for the error, I get: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
From a little bit of research it seems this is a problem with my 'data source name'. I put my database file in the project folder, and the name is correct. Why is it not finding it?
EDIT: No, the database was the same on both computers. In the same folder as well.
EDIT: I think I may need to create a system dsm. Following the instructions on the internet dosent work though, because I dont have the same files as them..
EDIT: I've tried to install that but it hasn't made a difference. My version of access is 64 bit alongside my version of netbeans..
Try installing a database engine + JVM that are both running in the same archeticture (i.e. 32bit), otherwise, you would receive a mismatch exception. I assume your JVM is 64bit but your database engine is not, so try installing a 64bit engine from the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=13255

Access (.mdb) Database manipulation with jdbc

Background: Working on an application to be run on an Apache server hosted by Network Solutions. Friend/Customer insisted on using an Access Database instead of SQL database.
Current Problem: Wrote a Java test program to make sure I can connect to the database before I dive head first into writing the whole backend. When I run this code on the JVM of the apache server the final product will be hosted:
import java.sql.*;
import java.io.*;
public class test {
public static void main(String[] args) {
try {
Class driverClass = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
DriverManager.registerDriver((Driver) driverClass.newInstance());
// set this to a MS Access DB you have on your machine
String filename = new File(".").getCanonicalPath() + "/ITEMS.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim(); // add on to the end
// now we can get the connection from the DriverManager
System.out.println(database);
Connection conn = DriverManager.getConnection( database );
} catch (Exception e) {
System.out.println("Error: " + e.getMessage() + " " + e.getLocalizedMessage());
e.printStackTrace();
}
}
}
I get a null pointer exception on the line Connection conn= DriverManager.getConnection( database)
Here is the stacktrace:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:436)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at test.main(test.java:20)
To write this test I used this as my primary source: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2691&lngWId=2
String strconnect="jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ="
Sring filename="some path";
StringBuilder a =new StringBuilder();
a.append(strconnect);
a.append(filename);
String db = a.toString();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c= DriverManager.getrConnection(db,"","")
Statement stmt = c.createStament();
String query = "some query";
stmt.executeQuery(query);
c.close();
Never get canonical Path, Either Specify the path of the access file or use JFile Explore and get path
also don't forget to close connection
Since you mention apache, I will presume that the server is running Linux or BSD.
In that case, please have a look at the following:
Connecting to access database from linux
Good Linux ODBC drivers for Access are expensive! (US$850 for a single machine!)
There is no default drivers for Access provided on linux, and the JDBC ODBC won't work unless you install one.
Unless there is a very special and overwhelming good reason for using an Access database as the backend to a website on a linux server, tell your friend that this is not technically or even economically coherent.
If you need a lightweight database on the server, use SQLite: it's free, there is good support for connecting to it from Java in linux, there is good tooling (even browser plugins), and you can always convert that database to Access if your friend want to get an Access backup once in a while.
Otherwise, go for PostgreSQL or MySQL like everyone does (generally for a good reason).

General JDBC Setup

So I have a MySQL database set up on a Debian server and it works fine from a phpMyAdmin client. I'm currently working on a project to write a Java server that would be able to use the MySQL database that is already on this server through a JDBC connection. I've looked at many tutorials and documentations but all of them seem to just explain how to do client-side code, but I have yet to figure out how to even successfully open a JDBC connection to the server. As far as I am concerned, I believe that program has the drivers properly set up because it's not crashing anymore (I simply direct the Java Build Path of my program to the Connector/J provided by MySQL). As far as my program goes, this is what it looks like...
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
System.out.println("Started!");
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
System.out.println("Driver registered. Connecting...");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "password");
System.out.println("Connected!");
conn.close();
} catch (SQLException e) {
System.out.println("Error!");
e.printStackTrace();
}
}
}
This is what's printed...
Started!
Driver registered. Connecting...
It's as if the DriverManager.getConnection(String) just freezes there. I'm sure this is a problem with the server because when I intentionally misspell localhost, or an IP address, the program crashes within 20 seconds. This just hangs there forever.
Sorry about this wall of text, but my final question is if anyone has any information what I should do or install on the server to get this to work? Thank you so much!
Try following:
public class MySqlDemo {
public static void main(String [] args) {
java.sql.Connection conn = null;
System.out.println("SQL Test");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?user=root&password=");
}
catch (Exception e) {
System.out.println(e);
System.exit(0);
}
System.out.println("Connection established");
}
You have to provide the name of the Schema to which you are connecting. Usually, the port is also added.
This is a sample connection string:
jdbc:mysql://repos.insttech.washington.edu:3306/johndoe?user=johndoe&password=jddb
3306 is the port and the first instance of johndoe is the name of the Schema. The second instance of johndoe is the username.
It could be that the Connector/J library is trying to use a named pipe to connect to the MySQL server rather than using TCP/IP and for some reason the named pipe isn't available. Try specifying a port number.
You may also want to try turning on some logging in Connector/J's configuration as described here.
Try putting port number and schema there
Try logging into database using some SQL client, may be SQL console
Try other drivers, may be some newer or perhaps older

A problem connecting to a MySQL DB using JDBC

Here's how I'm trying to connect:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
throw new DbConnectionException();
}
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
throw new DbConnectionException();
}
I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:
com.mysql.jdbc.CommunicationsException:
Communications link failure due to
underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException MESSAGE:
java.net.ConnectException: Connection
refused
...
Possibly a url issue. If your code is pointing to MySQL localhost, try changing localhost to 127.0.0.1 on your url.
E.g.:
jdbc:mysql://localhost:3306/MY_DB
to
jdbc:mysql://127.0.0.1:3306/MY_DB
And see if this works.
did you run the mysql browser from the same machine where the code is running? What I am getting at is the permissions in mysql can be host-specific, and depending on how you set them up you might not be able to connect from the machine where the code is running.
Also, you might want to double check the url, name, pword again, perhaps with log statements or a debugger to make sure there are no typos, trailing whitespaces, etc...
Double check the format of your url. It should start with "jdbc:mysql:". Make sure you are using a current version for the driver as well.
Check that you can connect to the database from the mysql admin tool, that will drive out whether your mysql is running and that the port is open.
In my case the problem was that I was using a connection from emulator to localhost.
If you use emulator to localhost don't use localhost value in connection String but use 10.0.2.2 instead:
jdbc:mysql://10.0.2.2:3306/MY_DB
Hope this helps.

Categories

Resources