im trying to use phpMyAdmin as DB on my javafx apps but everytime I open my apps, no data are being displayed and there are errors.
This is my Connect class:
public java.sql.PreparedStatement connectDatabase() throws Exception{
java.sql.Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://sql6.freemysqlhosting.net/hostingserver:3306","dbUserName","dbPassword");
java.sql.PreparedStatement ps = conn.prepareStatement("Select ORNUM,AMOUNT from receipt");
return ps;
}
Related
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;
}
}
From groovy script in SoapUI I need to connect to a mysql database to perform some queries. The problem is that due to security reasons no external access is possible.
Therefore it is required to get an ssh access (like a tunnel) and invoke mysql locally.
Initially I was reading the below project properties and then connect to mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
But this didn't work so now it is required to establish first a ssh connection to the server with the IP 10.255.255.122 and then open the mysql connection locally. So I guess the Server Url will change to:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
But I don't know how to set first the ssh connection to the server.
Can someone help me with this?
Thanks.
Have a look at http://forum.soapui.org/viewtopic.php?t=15400 and connect to remote mysql database through ssh using java
It will give you an idea about implementing it in soapUI.
Below is the code by Ripon Al Wasim which is available as an answer at the stackoverflow link mentioned above
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Does anyone know if the SQuirreL SQL Client is compatible with QODBC? If not is there a plugin for SQuirreL to enable so?
Any insight would be appreciated as I have never used either.
An Example of QODBC Driver working with the Java ODBC Bridge Product
Note: Below are some example code from one of our happy customers:
// QuickBooks variables
Connection con =null;
Statement stmt = null;
ResultSet rs = null;
// parameters for QuickBooks database
static final String url = "jdbc:odbc:quickbooks";
// "quickbooks" is a System DSN that is the name of the QODBC driver
// On WindowsXP it can be set up at Control Panel > Administrative Tools >
// Data Sources (ODBC)
static final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
public static void main(String[] args) throws Exception {
InsertCustomers t = new InsertCustomers();
}
public InsertCustomers() throws Exception {
try {
Class.forName(driver);
con = DriverManager.getConnection(url);
stmt = con.createStatement();
System.out.println("Querying QB customer table");
rs = stmt.executeQuery("SELECT * FROM customer");
JDBC is supported by QODBC - thanks!
http://support.flexquarters.com/esupport/index.php?/Knowledgebase/Article/View/383/0/how-can-qodbc-driver-work-with-the-java-odbc-bridge-product
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.
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.