How to import MySQL using Gradle and connect into JavaFX - mysql

I'm using IntelliJ IDEA and JavaFX 10 for my practice learning. I want to connect MySQL and import it using Gradle.
I found multiple example in internet but I din't found any latest, most of the function is already depreciated and reading so much different example makes me confused.

You may want to read first the official documentation instead of reading multiple example.
I assume that you are beginner.
1.) First thing to do is to Download the MySQL Installer to intall the Server into your machine. Remember that things won't work without this.
During the installation you will need to set your Server PORT, root password or add a new user, just remember the Server PORT and root Password and leave things in default.
2.) Go to Maven Central. We need to import the MySQL Connector. In order to import the MySQL Connector into Gradle we need to get the correct group, name and version for it.
You notice that in Maven Central there are multiple selection on how you can import the jar into your project, this time we want to import it using Gradle,
so you have to choose the Gradle and copy the code: compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
NOTE - In order to avoid problems, just always choose and use the latest version of MySQL Installer and MySQL Connector, at the moment the latest version is 8.0.11.
3.) In IntelliJ IDEA, in order to import in Gradle, in your project there is build.gradle click it to open then paste the code you copied in dependencies.
it should look like:
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
}
4.) Create a class where you want to connect into MySQL, the below code is my example.
Main.Class
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args){
Connection conn = null;
String user = "whatEverUserNameYouSetup";
String password = "whatEverPasswordYouSetup";
String database = "whatEverTheNameOfYourDatabase";
int port = 3306; //default port, change it depending on your setup
try {
Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:" + port + "/" + database, user, password);
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
NOTE: The documentation is your friend.
UPDATE: If you run on error something like
Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
then you need to set useSSL to false, the code will be look like:
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Main {
public static void main(String[] args){
Connection conn = null;
Properties properties = new Properties(); //I use Properties to make things easer.
properties.setProperty("user", "root");
properties.setProperty("password", "YourPassword");
properties.setProperty("useSSL", "false"); //Set useSSL to false to solve the problem.
try {
Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306", properties);
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

Related

Run Sikuli commands on Katalon-Studio

I'm trying to run a test that contains Sikuli methods in it via Katalon-Studio.
I added the necessary libraries but still getting this error when it tries to execute the Sikuli command:
[error] ResourceLoaderBasic: checkLibsDir: libs dir is not on system path: C:\Users\roinr\git\QA\Drivers\libs
[action] ResourceLoaderBasic: checkLibsDir: Please wait! Trying to add it to user's path
[info] runcmd: reg QUERY HKCU
[info] runcmd: reg QUERY HKEY_CURRENT_USER\Environment /v PATH
[error] ResourceLoaderBasic: checkLibsDir: Logout and Login again! (Since libs folder is in user's path, but not activated)
[error] Terminating SikuliX after a fatal error! Sorry, but it makes no sense to continue!
If you do not have any idea about the error cause or solution, run again
with a Debug level of 3. You might paste the output to the Q&A board.
This is my script:
import internal.GlobalVariable as GlobalVariable
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.sikuli.script.Key;
import org.sikuli.script.Screen;
//Initializing server
System.setProperty("webdriver.chrome.driver", "C:/selenium/chromedriver.exe");
//Initializing variables
ChromeDriver wd = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(wd,10);
Screen s = new Screen();
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
System.out.println("*** Login Sikuli ***");
wd.get("https://autoqa-materials-zone.firebaseapp.com/login");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[2]/div/input")));
wd.findElement(By.xpath("//div[2]/div/input")).click();
try { Thread.sleep(1000l); } catch (Exception e) { throw new RuntimeException(e); }
s.paste("<USERNAME>");
try { Thread.sleep(1000l); } catch (Exception e) { throw new RuntimeException(e); }
s.type(Key.TAB);
try { Thread.sleep(800l); } catch (Exception e) { throw new RuntimeException(e); }
s.paste("<PASSWORD>");
try { Thread.sleep(1000l); } catch (Exception e) { throw new RuntimeException(e); }
wd.findElement(By.xpath("//form[#id='form']//paper-button[.='login']")).click();
try { Thread.sleep(5000l); } catch (Exception e) { throw new RuntimeException(e); }
wd.quit();
Hope you can help me with that,
thanks.

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

Access to MySQL using Java Servlet?

The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?
You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.
David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);
First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test

javafx connection to mysql [closed]

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.

SQLException - Connection reset error

I am trying to establish a jdbc connection with SQL Server 2008 R2, using the SQLJDBC4 jar file and JDK 1.6. I am using Netbeans IDE and have added the SQLJDBC4 jar and added the path to the database in the 'databases' section in the services. The code is as below:
package connect2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connect2 {
public static void main(String[] args) throws SQLException {
Connection conn;
conn = null;
System.out.println("Done....");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection ("jdbc:sqlserver://172.17.39.13\\CRM:1433;databaseName=crm_xchanging","crm_xchanging","Welcome001");
System.out.println ("Database connection established");
}
catch (ClassNotFoundException e)
{
System.out.println (e);
}
catch (SQLException ex)
{
System.out.println(" error");
}
finally
{
if (conn != null)
{
try{
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM usertable");
System.out.println("User Name: " );
while (res.next()) {
String employeeName = res.getString("user_name");
System.out.println(employeeName);
}
conn.close();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex = ex.getNextException();
// For drivers that support chained exceptions
}}
}
}
}
}
This is the output I'm getting:
run:
Done....
Database connection established
SQLException information
Error msg: Connection reset
SQLSTATE: 08S01
Error code: 0
BUILD SUCCESSFUL (total time: 1 second)
I don't think there is any mistake in the code or the JDK. I have also tried to set the max no. of active connections for SQL Server as 0 (infinite). How do I solve this problem?
There is a known bug introduced in Java 6u29 that causes SSL failure specifically with SQL Server 2008 R2. An Atlassian Fisheye troubleshooting page suggests a fix was incomplete.
Oracle delivered a fix in 6u30, although for at least one affected
client not even Java 1.7 worked.
On my development team we have found this bug to impact Java 8 at as well. One of the recommendation in the Fisheye article is to disable CBC protection using a JVM flag and that has also worked for me for SSL Java 8 SSL with a SQL Server 2008 R2 connection.
-Djsse.enableCBCProtection=false
The other suggestion is to revert to Java 1.6.0_24.