javafx connection to mysql [closed] - mysql

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
we are building javafx application which will be presenting information about stocks.
Here is the website:
http://analiza.host-ed.me/
But we've got a huge problem. Every free hosting doesn't allow remote mysql connection. And there is my question. When our site is on the server (which i linked) is this remote connection or local connection?
When we put this javafx app as a site it can't connect like it was on the local machine...
Is there any solution? Thanks for help.
(we need to use free hosting, because it's only a school project..)

You can access MySQL from JavaFX. But JavaFX runs on a client and something like php usually runs on a server. You will need a connection from your java app to MySQL. As your hosting provider won't allow you to directly connect to the database port from your Java Client App, you will need some other way to connect.
You could tunnel through port 80, you could run a servlet (or php server code, etc) to intercept incoming traffic and proxy database calls through a HTTP based REST interface or you could install the DB locally on the client.
I'm going to assume, for a school project, it's ok for each client machine to have it's own database. In which case, instead of using MySQL, use a lightweight Java database like H2, bundle it with your app by including it's jar as a dependent library, package the app plus DB jar as a signed WebStart application using the JavaFX packaging tools and host the files generated by the packaging tools at your hosting provider.
Update
Here is a sample application which uses a local H2 database on the client computer.
import java.sql.*;
import java.util.logging.*;
import javafx.application.Application;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class H2app extends Application {
private static final Logger logger = Logger.getLogger(H2app.class.getName());
private static final String[] SAMPLE_NAME_DATA = { "John", "Jill", "Jack", "Jerry" };
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final ListView<String> nameView = new ListView();
final Button fetchNames = new Button("Fetch names from the database");
fetchNames.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
fetchNamesFromDatabaseToListView(nameView);
}
});
final Button clearNameList = new Button("Clear the name list");
clearNameList.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
nameView.getItems().clear();
}
});
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
layout.getChildren().setAll(
HBoxBuilder.create().spacing(10).children(
fetchNames,
clearNameList
).build(),
nameView
);
layout.setPrefHeight(200);
stage.setScene(new Scene(layout));
stage.show();
}
private void fetchNamesFromDatabaseToListView(ListView listView) {
try (Connection con = getConnection()) {
if (!schemaExists(con)) {
createSchema(con);
populateDatabase(con);
}
listView.setItems(fetchNames(con));
} catch (SQLException | ClassNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
logger.info("Getting a database connection");
Class.forName("org.h2.Driver");
return DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
}
private void createSchema(Connection con) throws SQLException {
logger.info("Creating schema");
Statement st = con.createStatement();
String table = "create table employee(id integer, name varchar(64))";
st.executeUpdate(table);
logger.info("Created schema");
}
private void populateDatabase(Connection con) throws SQLException {
logger.info("Populating database");
Statement st = con.createStatement();
int i = 1;
for (String name: SAMPLE_NAME_DATA) {
st.executeUpdate("insert into employee values(i,'" + name + "')");
i++;
}
logger.info("Populated database");
}
private boolean schemaExists(Connection con) {
logger.info("Checking for Schema existence");
try {
Statement st = con.createStatement();
st.executeQuery("select count(*) from employee");
logger.info("Schema exists");
} catch (SQLException ex) {
logger.info("Existing DB not found will create a new one");
return false;
}
return true;
}
private ObservableList<String> fetchNames(Connection con) throws SQLException {
logger.info("Fetching names from database");
ObservableList<String> names = FXCollections.observableArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name from employee");
while (rs.next()) {
names.add(rs.getString("name"));
}
logger.info("Found " + names.size() + " names");
return names;
}
}
There is a corresponding NetBeans project for this sample which will generate a deployable application. The project can be tested in webstart and applet mode.
For the sample, the database is stored on the user's computer (not the server from which the application was downloaded) and persists between application runs.
The exact location depends on the jdbc connection initialization string. In the case of my sample the database goes in the user's directory jdbc:h2:~/test, which is OS and User specific. In the case of me for Windows it ends up at C:\Users\john_smith\test.h2.db. Using a jdbc connection string such as jdbc:h2:~/test is preferable to a string such as jdbc:h2:C:\\Baza because a string with C:\\ in it is platform specific and won't work well on non-windows systems. For further information on h2 jdbc connection strings refer to the connections settings in the h2 manual.
The h2 system works such that if the database file already exists, it is reused, otherwise a new database file is created. If you modify the database, shut the application down, then load the application again a week later, it is able to read the data created the week before.

Related

Cannot connect to AWS MySQL using Java SDK and IAM Role / Instance Profile

I want to connect to an RDS Aurora instance using an Instance Profile that utilizes STS to assume a role so that I don't need to hard code my password in the solution. I'm getting an error that states my user doesn't have access. However, when I hard code the connection string with username and password, I'm able to connect using the same user. I've checked db user permissions and they're correct. I've also tried using all permissions in the role. I've added logging to check that I'm receiving a token and I am. Any ideas or help is appreciated. Amazon's documentation that I've been following is: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.Java.html
My Code:
public final class Database {
private static String jdbcUrl = "jdbc:mysql://" + DockerConstants.PersistenceStoreUrl + ":" + DockerConstants.PersistenceStorePort + "/dbname";
private Database() {
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(jdbcUrl, setMySqlConnectionProperties());
}
static String generateAuthToken(){
RdsIamAuthTokenGenerator generator = RdsIamAuthTokenGenerator.builder()
.credentials(InstanceProfileCredentialsProvider.getInstance())
.region(EC2MetadataUtils.getEC2InstanceRegion())
.build();
String authToken = generator.getAuthToken(
GetIamAuthTokenRequest.builder()
.hostname(DockerConstants.PersistenceStoreUrl)
.port(DockerConstants.PersistenceStorePort)
.userName(DockerConstants.PersistenceStoreUserName)
.build());
return authToken;
}
private static Properties setMySqlConnectionProperties() {
Properties mysqlConnectionProperties = new Properties();
mysqlConnectionProperties.setProperty("verifyServerCertificate","false");
mysqlConnectionProperties.setProperty("useSSL", "false");
mysqlConnectionProperties.setProperty("user", DockerConstants.PersistenceStoreUserName);
mysqlConnectionProperties.setProperty("password",generateAuthToken());
return mysqlConnectionProperties;
}
}

How to set up JDBC Connection Poll to mySql on Jetty server in IntelliJ Vaadin Project

Pls explain me this like i am a retard kid. I am stuck at this point for three days. There so so much documentation for multiple use of JDBC, but when i do it one it won't work for me.
So I build project whit maven vaadin build:
.
Now I need to connect to my MySQL database. I will need to push data once per day. Just for store. I need one simple solution which will be good for my use.
This code work for me all ready but now i am trying whit Pool:
public class Povezavapool {
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/patrioti");
dataSource.setUsername("root");
dataSource.setPassword("1234567890");
}
private Povezavapool() {
//
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
But now i trying to do smt like this because I read it it is faster and better. I have no idea how to set up it.
public static JDBCConnectionPool getConnectionPool() {
SimpleJDBCConnectionPool pool = null;
try {
pool = new SimpleJDBCConnectionPool("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/patrioti", "rooot",
"1234567890");
} catch (SQLException e) {
e.printStackTrace();
}
return pool;
}

Cannot retrieve document from couchbase lite when adding documents to couchbase server using admin UI

I am trying to add documents to couchbase server(admin UI) and then trying to retrieve it using couchbase Lite via sync gateway but unable to do so. What I am trying to achieve is I already have a lot of data in couchbase server now I want my mobile app to use it and because that data was not added using sync gateway I want to achieve something like I added data using web now I want my couchbase lite to connect to that couchbase server and retrieve data. Is there any way to do it? or only data that has been added using sync gateway can be retrieved?
EDIT 1 Added Source Codes
Below is the android app code
package com.couchbase.examples.couchbaseevents;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Manager;
import com.couchbase.lite.android.AndroidContext;
import com.couchbase.lite.replicator.Replication;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
public static final String DB_NAME = "couchbaseevents";
final String TAG = "CouchbaseEvents";
Database database = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Begin Couchbase Events App");
Manager manager = null;
try {
manager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS);
database = manager.getDatabase(DB_NAME);
} catch (Exception e) {
Log.d(TAG, "Error getting database", e);
return;
}
/*try {
database.delete();
} catch (Exception e) {
Log.e(TAG, "Cannot delete database", e);
return;
}*/
try {
startReplications();
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
Document retrievedDocument = database.getDocument("123");
// display the retrieved document
Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
Log.d(TAG, "End Couchbase Events App");
}
private URL createSyncURL(boolean isEncrypted){
URL syncURL = null;
String host = "http://172.16.25.100";
String port = "4986";
String dbName = "sync_gateway";
try {
//syncURL = new URL("http://127.0.0.1 :4986/sync_gateway");
syncURL = new URL(host + ":" + port + "/" + dbName);
} catch (Exception me) {
me.printStackTrace();
}
Log.d(syncURL.toString(),"URL");
return syncURL;
}
private void startReplications() throws CouchbaseLiteException {
Replication pull = database.createPullReplication(this.createSyncURL(false));
Replication push = database.createPushReplication(this.createSyncURL(false));
pull.setContinuous(true);
push.setContinuous(true);
pull.start();
push.start();
if(!push.isRunning()){
Log.d(TAG, "MyBad");
}
/*if(!push.isRunning()) {
Log.d(TAG, "Replication is not running due to " +push.getLastError().getMessage());
Log.d(TAG, "Replication is not running due to " +push.getLastError().getCause());
Log.d(TAG, "Replication is not running due to " +push.getLastError().getStackTrace());
Log.d(TAG, "Replication is not running due to " +push.getLastError().toString());
}*/
}
}
"123" is the document id of document I created in CouchBase server using admin UI
As you can see I first deleted the database( commented part) to make sure there is no document in database and then ran the above replication code.
Below is the sync gateway config file
{
"log":["CRUD+", "REST+", "Changes+", "Attach+"],
"interface":":4986",
"adminInterface":":14985",
"databases": {
"sync_gateway": {
"server":"http://172.16.25.100:8091",
"bucket":"sync_gateway",
"sync":`
function (doc) {
channel (doc.channels);
}`,
"users": {
"GUEST": {
"disabled": false,
"admin_channels": ["*"]
}
}
}
}
}
I also want to ask is there any UI or command line to access CBL. I am currently using CBL in android studio so I dont know how to access its UI or command line
Just for the information, I am able to push data from CBL to CouchBase server
We can solve the above issue by shadowing. If I want to sync my data from the already made bucket to sync gateway bucket shadowing is required. More about Shadowing here

jsp mysql server connection timeout

hi i am doing an jsp project. and i deploy my project on apache tomcat. i use mysql as databese.
when i deploy project on remote server it is run good. but after some hours it gives me sql error. then i go back my apache server and start projecet again it run and after some hours it gives me same sql error again. i dont know the problem. is that caused from my java connection code or it is about mysql server. can some one tell me why it gives me sql error.?
public class ConnectionManager {
private String className = "com.mysql.jdbc.Driver";
private String userName ="username";
private String password = "password";
private String url = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
/**
* #uml.property name="connectionInstance"
* #uml.associationEnd
*/
private static ConnectionManager connectionInstance = null;
public ConnectionManager(){
}
public static synchronized ConnectionManager getInstance() {
if(connectionInstance == null) {
connectionInstance = new ConnectionManager();
}
return connectionInstance;
}
public Connection getConnection(){
Connection conn = null;
try {
Class.forName(className);
conn = DriverManager.getConnection (url, userName, password);
System.out.println("Connection Established");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
MySQL has a default connection timeout of 8 hours. So this means that you've kept a SQL connection open for too long. Your code suggests that you're creating only one connection on application's startup and reusing it application wide. This is very bad. This is not threadsafe.
You need to change your code so that you're not declaring and storing the SQL Connection as a static or instance variable anywhere in your code. Instead, it should be declared, created and closed within the shortest possible scope. Preferably within the very same method block as where you're executing the SQL query.
Here's a minor rewrite of your ConnectionManager which does the job properly:
public class ConnectionManager {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String USERNAME ="username";
private static final String PASSWORD = "password";
private static final String URL = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
static {
try {
Class.forName(DRIVER);
}
catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(DRIVER + " missing in classpath!", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
Use it as follows:
public class SomeDAO {
public SomeEntity find(Long id) throws SQLException {
Connection connection = null;
// ...
try {
connection = ConnectionManager.getConnection();
// ...
}
finally {
// ...
if (connection != null) try { connection.close(); } catch(SQLException ignore) {}
}
return someEntity;
}
To improve connecting performance, use a connection pool instead of DriverManager.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Are you closing connections properly after using them.

jdbc connection of mysql to html

Hi i have the following file to connect mysql database to html files. But i am having trouble connecting it. Can anyone tell me where i find the locations.
What should i replace "jdbc:mysql://localhost/zulfiqar" with for it to work on my computer? where do i find this?
And is there anything else i have to change to make it work on my computer? this was a piece of code i found on the internet which i am trying to make work so i can understand how to do it, but i am struggling.
Thanks in advance!
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUserEnquiryForm extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
/**Process the HTTP Get request*/
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException{
String connectionURL = "C:\Program Files(x86)\MySQL Server 5.0\bin\mysql.exe";
Connection connection=null;
ResultSet rs;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uId = req.getParameter("userId");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("address1");
String address2 = req.getParameter("address2");
String town = req.getParameter("town");
String county = req.getParameter("country");
String zipcode = req.getParameter("zipcode");
try {
// Load the database driver
Class.forName("org.gjt.mm.mysql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection
(connectionURL, "root", "admin");
//Add the data into the database
String sql =
"insert into emp_details values (?,?,?,?,?,?,?,?)";
PreparedStatement pst =
connection.prepareStatement(sql);
pst.setString(1, uId);
pst.setString(2, fname);
pst.setString(3, sname);
pst.setString(4, address1);
pst.setString(5, address2);
pst.setString(6, town);
pst.setString(7, county);
pst.setString(8, zipcode);
int numRowsChanged = pst.executeUpdate();
// show that the new account has been created
out.println(" Hello : ");
out.println(" '"+fname+"'");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: "
+ e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: "
+ e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
// Always close the database connection.
try {
if (connection != null) connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
Some additional information about how it's failing might be useful.
1) Is it failing to make the socket connection (implying your service isn't running), or
2) Did it fail to initialize the driver? I'm not familiar with the one you listed. A more common alternative is "sun.jdbc.odbc.JdbcOdbcDriver".
3) Did you connect and simply fail authentication with user "root" and password "admin"?
What should i replace "jdbc:mysql://localhost/zulfiqar" with
Ans: It is the connection url. It does mean your MySQL database is running on localhost server (with default port) and you are connecting to 'zulfiqar' database. So first line under doPost() should be :
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Next, you are using org.gjt.mm.mysql.Driver driver for JDBC connection. It was initially developed by a hobbyist. It's later donated to MySQL where they renamed the package/classname. The old classname is kept for backwards compatibility reasons, but you should update it to com.mysql.jdbc.Driver and add mysql-connector-java-*-bin.jar in your WEB-INF/lib folder.
Next thing you are using :
connection = DriverManager.getConnection(connectionURL, "root", "admin");
So you are loading a connection from the connectionURL and accessing it with root user and admin password. Make sure these are correct in your case.
Last point is, you are inserting into emp_details table. Make sure you have this table already created in zulfiqar database with all required columns. And the number of '?' marks in the sql string should match the number of times you are doing pst.setString(index, data), otherwise you will get Invalid parameter index error.