phpMyAdmin and Java Connection - java

I am trying to connect my java program to a database that i have created using phpmyadmin using a university server. so the database is on the university server. how do i get the connection to the db from the java program? i have tried this code, but it gives me an error message?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Connector {
Connection con;
PreparedStatement stmt;
ResultSet rs;
Connector()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("https://NAMEHIDDEN.soi.city.ac.uk:5454/~kdhy546","root","");
stmt=con.prepareStatement("select * from staff where username=? and password=?");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I am not too sure even, whether this is the correct url to the database? how do i determine the exact link to the database in phpmyadmin?

phpMyAdmin in not a DBMS, it's an UI. If it's a MySQL database, you must use the MySQL JDBC

I have never used phpMyAdmin, but according to this tutorial you should get the connection string if you navigate to the MySQL Account Maintenance Section.
Another thing I am noticing is that you are missing your password in your connection, so without a password your application will not be able to connect.
Lastly, whenever you post a question on SO regarding some code which yields an error, please make sure you include the error, it helps us help you :).

Use the following code.
This is the java part:
import java.net.*;
public class mc
{
public static void main(String args[])
{
try
{
String username="ankur",password="ankur",fname="Shubhendu",ip="12345",lname="Goswami";
String up= "username=" + username + "&password=" + password + "&fname=" + fname + "&lname=" + lname + "&ip="+ ip;
URL url=new URL("http://127.0.0.1:80/alias1/index.php?"+up);
URLConnection urlc=url.openConnection();
urlc.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String str;
while((str=br.readLine())!=null)
{
System.out.print(str);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
PHP part: Anything you will echo from PHP will be stored in String str in Java code:
<?php
mysql_connect("localhost","root","")or die("unable to connect to server");
mysql_select_db("db_name") or die("Unable to connect to database");
$username=$_GET['username'];
$password=md5($_GET['password']);
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$ip=$_GET['ip'];
if(isset($username) && isset($password) && isset($fname) && isset($lname) && isset($ip))
{
$query="INSERT INTO tablename values('$username','$password','$fname','$lname','$ip')";
$fire=mysql_query($query);
}
?>
Hope it works.

Your URL to the database you created with phpMyAdmin is wrong. It should look something similar to:
jdbc:oracle:thin:#//myhost:1521/orc
I recommend you to have a web search for some good Java tutorials on this subject. :)

Related

DB Derby Database stops functioning once connected to DBeaver

Here is my application's code to create the database, connect to it, and make a table in the database called Accounts.
package eportfolio.application;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* #author valeriomacpro
*/
public class HomePage extends javax.swing.JFrame {
public static String username;
public static String password;
public static int SelectedPost;
/**
* Creates new form HomePage
*/
public static boolean doesTableExists (String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public HomePage() {
initComponents();
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
} catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
}
Additionally, here is my code that interacts with the Accounts table.
try
{
String databaseURL = "jdbc:derby:eportdatabase;";
Connection con1 = DriverManager.getConnection(databaseURL);
Statement st = con1.createStatement();
String sql = " INSERT INTO Accounts VALUES ('"+txtNewUsername.getText()+"','"+txtNewPassword.getText()+"') ";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Account Info Saved!");
txtNewUsername.setText("");
txtNewPassword.setText("");
txtNewConfirm.setText("");
}
When I run the application, the code works fine. However, if I open DBeaver and connect it to my database, then the following error message comes up. Does not come up if DBeaver is closed, even if it is connected to the database.
Message:Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XJ040: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
SQLState:XSDB6
Error Code:45000
Message:Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Why is this? Am I connecting the Database to DBeaver incorrectly? Or am I coding the database incorrectly in Netbeans? It could be that my drivers and db derby version are old, but I have not been able to find help on that online either. Also important to know that the table does show up in DBeaver, but does not update. I have to delete the database folder in my application's folder every time I want to use the application with DBeaver open. Any help appreciated.
By using this line of code:
String databaseURL = "jdbc:derby:eportdatabase;";
you are using Derby in the "embedded" configuration. With Embedded Derby, only one Java application at a time can use the database. Other applications that try to use it concurrently are rejected with the message
Another instance of Derby may have already booted the database
as you saw when you tried it.
There are other configurations in which Derby can be deployed and run; specifically there is a Client-Server configuration in which multiple applications may all run as clients, and may connect to the same Derby server, allowing the applications to run concurrently.
To learn more about these aspects of Derby, start here: https://db.apache.org/derby/docs/10.15/getstart/cgsquck70629.html

Connection between Java and MySql

I am trying to make a connection between Java and my data base. I am using Eclipse and xampp. I am almost convinced that I have good config of Eclipse and xampp, but maybe I missed something. I searched a lot on the Internet, but I have not found the solution.
My error are:
SQLException: Could not create a connection to database server. Attempted to reconnect 3 times. Giving up.
SQLState: 08001
VendorError: 0
Xampp -
Xampp config
Eclipse -
I have jar files in the workspace folder.
Eclipse config
phpmyadmin -
I do not need a password to log into localhost/phpmyadmin and I have only one record in DB.
Code
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC2 {
static String daneZBazy;
static String polaczenieURL = "jdbc:mysql://localhost:3306/heroes.db?
autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "root";
public static void main(String[] args) {
// Question to DB
String query = "Select * FROM heroestab";
Connection conn = null;
try {
// Connection parameters
conn = DriverManager.getConnection(polaczenieURL, login, password);
// MySQL Driver
Class.forName("com.mysql.jdbc.Driver");
// Start question to DB
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
wyswietlDaneZBazy(rs);
}
conn.close();
}
//throws exception
catch (ClassNotFoundException wyjatek) {
System.out.println("Driver error");
}
catch (SQLException wyjatek) {
wyjatek.printStackTrace();
System.out.println("Login problem. Check, username, password, DB name, IP adress");
System.out.println("SQLException: " + wyjatek.getMessage());
System.out.println("SQLState: " + wyjatek.getSQLState());
System.out.println("VendorError: " + wyjatek.getErrorCode());
}
}
static void wyswietlDaneZBazy(ResultSet rs) {
try {
daneZBazy = rs.getString(1);
System.out.println("\n" + daneZBazy + " ");
daneZBazy = rs.getString(2);
System.out.println(daneZBazy + " ");
daneZBazy = rs.getString(3);
System.out.println(daneZBazy);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Please verify that both the username and password are correct.
I need the full stack trace from:
wyjatek.printStackTrace();
If the username (root) and password are incorrect, you will see the below line in your stacktrace:
Access denied for user 'root'#'localhost' (using password: YES)
If I remember correctly, with default xampp config, you can try this:
user: root
password: [blank]
static String login = "root";
static String password = "";
I can see my databases useing cmd:
C:\xampp\mysql\bin > mysql -u root -p
Enter
show databases ; and then I can see all databases which I have on localhost. When i
chose heroes and I can select * from heroes ;
Picture:
Database cmd

How to use XAMPP MySQL database with my Java Application?

I have used in the past few months XAMPP with MySQL database(s), which were created and modified with phpMyAdmin on localhost, for my university JavaEE projects. The MySQL database and Apache server are started from the XAMPP Control Panel. Everything went fine.
Now I am developing my own Java Desktop Application using JavaFX/Scene Builder/FXML and I want to use a database to store and load various information processed by the Java Application through JDBC.
The question is, how to start the MySQL database on localhost, without using the XAMPP Control Panel manually, when I finish my Java Application and deploy it as stand alone program and start it just from a single shortcut?
Any way to make the shortcut of the program also start the MySQL database on my PC before/while it starts the Java Application? Or maybe there is a way to do that inside the Java code? Or maybe some other way, that is not known to me?
I am not strictly determined on using only the XAMPP/MySQL/phpMyAdmin setup, it is just already all installed on my PC and I know how to work with it, thus the easiest solution so far. So if there is some better way/database setup for home/small applications, please feel free to suggest some :). I am not sure at all if what I want to do is possible with the XAMPP setup.
Side note: I persist on using localhost DB instead of Serialisation/Deserialisation with Java, because I want the Application to be independent of internet connection and yet have the opportunity to have a ready DB to be transferred to an online DB, if such I decide to do it in the future.
On the root of the Xampp folder you have one mysql_start.bat and one mysql_stop.bat, for start/stop the mysql database included on the Xampp package.
You can use they in another bat you should create to start your Java Desktop application.
ProcessBuilder P1 =new ProcessBuilder("C:\\xampp\\mysql_start.bat");
P1.start();
ProcessBuilder P2 =new ProcessBuilder("C:\\xampp\\APACHE_start.bat");
P2.start();
You can do it like this -
To connect to the Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Statement statement;
//function to connect to the xampp server
public void DatabaseConnect(){
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/javafx","root","");
/*here javafx is the name of the database and root is the username of
your xampp server and the field which is blank is for password.
Because I haven't set the password. I have left it blank*/
statement = conn.createStatement();
System.out.print("Database Connected");
} catch (Exception e) {
System.out.print("Database Not Connected");
}
}
Below given are the various operations you can perform after connecting to the database.
//for inserting data
public void insert(){
try{
String insertquery = "INSERT INTO `tablename`(`field1`, `field2`) VALUES ('value1', 'value2'";
statement.executeUpdate(insertquery);
System.out.print("Inserted");
} catch(Exception e){
System.out.print("Not Inserted");
}
}
//for viewing data
public void view(){
try {
String insertquery = "select * from `table_name` where field = 'value1'";
ResultSet result = statement.executeQuery(insertquery);
if(result.next()){
System.out.println("Value " + result.getString(2));
System.out.println("Value " + result.getString(3));
}
} catch (SQLException ex) {
System.out.println("Problem To Show Data");
}
}
//to update data
public void update(){
try {
String insertquery = "UPDATE `table_name` set `field`='value',`field2`='value2' WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Updated")
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
//to delete data
public void delete(){
try {
String insertquery = "DELETE FROM `table_name` WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Deleted");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
Also, don't forget to add the JAR file in your system library. For this example, I have used mysql-connector-java-5.1.46

mySQL connection won't work

I just can't connect to mySQL using Eclipse and can't figure out why.
Here is my connection class :
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ConnexionBDD {
static String url = "jdbc:mysql://localhost:8888/Peoples?autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "";
static Connection connection = null;
static Statement statement = null;
static ResultSet result = null;
static String request = "";
public static void main (String[] args) {
System.out.println("will load driver");
loadingDrive();
System.out.println("will connect");
connection();
}
public static void loadingDrive() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch ( ClassNotFoundException e ) {
e.getMessage();
}
}
public static void connection() {
try
{
connection = (Connection) DriverManager.getConnection(url, login, password);
System.out.println("Connected");
statement = (Statement) connection.createStatement();
result = statement.executeQuery(request);
}
catch ( SQLException e )
{
System.out.println(e.getMessage());
} finally {
if ( result != null ) {
try {
result.close();
} catch ( SQLException ignore ) {
}
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
if ( connection != null ) {
try {
connection.close();
} catch ( SQLException ignore ) {
}
}
}
}
}
Here is the result in the console :
will load driver
will connect
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
I have the connector (mysql-connector-java-5.1.41-bin.jar) in the file WebContent/WEB-INF/lib.
I installed mySQL on my mac.
I installed MAMP, I can reach phpmyadmin and add a new database, but it's kind of weird though, phpmyadmin is already logged as default and clicking the "Exit" button does not disconnect me I don't know why..
The url of phpmyadmin is :
http://localhost:8888/phpmyadmin/index.php
Why can't I connect to mySQL ?
EDIT :
I changed my url with the right port (8889) after checking out the mySQL port on MAMP, but nothing changed in the output of the console.
MySQL and phpMyAdmin cannot be on the same port.
Are you sure that your MySQL is not running on the default port? 3306
UPDATE:
If you are not already using Maven, please do so. It will aid you in managing your packages. That way you can avoid your method: loadingDrive()
I just ran you code locally with a test database. It runs fine for me.
I did the following changes to your code:
I removed the loadingDrive()
Altered request to static String request = "SELECT 1";. This query string is good for testing if the connection to the database is working properly.
I printed the request to the console:
result = statement.executeQuery(request);
System.out.println(result.next());
I added the mysql jdbc connector to my pom.xml file:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
After this I ran the code and this is the console output:
will connect
Connected
true
I still think your MySQL port is wrong. Do you run MySQL locally? Can you connect to it with phpMyAdmin?
I tried to change the url to contain the wrong port. I then received:
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
So I strongly believe that your port is wrong. Can you try to change your url to the following?
static String url = "jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false";

Android Studio Sql Server Connection

I'm making an app in android studio with connection to a SQL database server, I have a problem in connecting to the database.
Code:
import android.util.Log; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import net.sourceforge.jtds.jdbc.*;
Log.i("Android", " MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
//String connString = "jdbc:jtds:sqlserver://localhost:1433/quehojaes;encrypt=false;user=Pc-PC;password=;instance=SQLEXPRESS;";
// String connString = "Data Source=localhost:1433;Initial Catalog=quehojaes;Integrated Security=True";
String connString ="jdbc:jtds:sqlserver://localhost:1433/quehojaes;";
String username = "Pc-PC";
String password = "";
conn = DriverManager.getConnection(connString);
Log.w("Connection", "open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from planta where id=1");
//Print the data to the console
while (reset.next()) {
dato = reset.getString(3);
Log.w("Data:", reset.getString(3));
Log.w("Data",reset.getString(2));
}
conn.close();
} catch (Exception e) {
Log.w("Error connection", "" + e.getMessage());
}
return dato;
}
.................................
I got an error at line (conn = DriverManager.getConnection (connString)), so I guess it is wrong user I'm trying to get into the database, I enter Windows user authentication with a local database and I have no password for that user called Pc.
There are lines discussed by failed login attempts I've tried.
Thanks for the help!
localhost means your current machine. That would be the phone. Since SQLServer isn't running on your phone, its the wrong string. Use your PCs IP address, and make sure you can access that port through any ISP or personal firewalls.
As an aside- this is a HORRIBLE way to do things. You have to put your password the the SQL server in your app. Its trivial to decompile it and own your data. Instead you should put up a web service inbetween the two, so only machines you own on your local network need to have the db password.

Categories