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
Related
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";
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.
So I am trying to connect to my database and display an item from the table.
The error I am getting is: SQL Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user 'Bob'#'%' to database 'TEST'
Is this connecting properly, and if so is the error that the credentials are wrong? And if they are wrong how is it connecting? Thank you
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://THISISTHEHOSTNAME";
String username = "Bob";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = null;
ResultSet rs = null;
//SQL query command
String SQL = "SELECT * FROM TEST";
stmt = connection.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("ProductName") + " : " + rs.getString("UnitPrice"));
}
}
catch (SQLException e)
{
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE)
{
System.out.println("Class Not Found Exception: "+ cE.toString());
}
You need to grant the proper privileges to the user that is connecting to the mysql db.
The message you are getting is informing you that while your user was able to connect to the database server, it was not allowed to access the database TEST.
Running the following command in the mysql console would grant such access:
GRANT ALL ON TEST.* TO 'BOB'#'%'
This is extremely permissive and you should keep in mind that db users should have the minimal amount of privileges possible and be restricted to the smallest range of hosts.
I used ShowIP Firefox add on and used the IP instead and didn't get any errors but I'm wondering if should return access granted and I'm unable to find an answer at the moment.
Here's a few things to do:
Check to see if your username and password are correct.
Did you add the username to the correct database? (This needs to be done in CPanel SQL)
Did you allow your database to get connection access from your IP address? (This also needs to be done in CPanel SQL)
create a new user in mysql check all global privileges > go to service in netbeans > database > mysql server at localhost > right click connect and fill username password
this work for me
Please try the code below:
import java.sql.*;
public class InsertPrepared {
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306//test","sanjib","");
PreparedStatement stmt=con.prepareStatement("insert into employee values(???)");
stmt.setInt(1,101);
stmt.setString(2,"Sampa");
int i=stmt.executeUpdate();
System.out.println(i+"Records is inserted");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
I am trying to insert data into Derby embedded database for my Desktop Application. But Derby is giving me error of Schema Not found error.
I have tried to solve error by creating schema as per username, but does not solve my problem. I searched internet, but none of given solution solved my problem.
package derbyd.ui;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AddStudent extends javax.swing.JFrame {
private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {
String conURL = "jdbc:derby:myDB;create=true";
String user = "SOURABH";
String passwd = "pass";
Connection con = null;
Statement st = null;
String query;
ResultSet rs = null;
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
query = "INSERT INTO SOURABH.MyTable VALUES('"+txt_name.getText()+"','"+txt_surname.getText()+"')";
st.executeUpdate(query);
System.out.println("Added Successfully");
}
catch(Exception e)
{
System.out.println("Error ->"+e);
}
}
}
According to the Frequently Asked Questions of Apache Derby, you will see that:
A schema is only created by CREATE SCHEMA or creating an object (table etc.) in that schema (this is implicit schema creation).
In your code, you need create the table first and then work like a charm.
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
st.executeUpdate("CREATE TABLE MyTable" +
"(name VARCHAR(255), surname varchar(255))");
System.out.println("Table created");
query = "INSERT INTO SOURABH.MyTable VALUES(" +
"'" + txt_name.getText() + "','" + txt_surname.getText() + "')";
st.executeUpdate(query);
System.out.println("Added Successfully");
The output is:
Connection established
Table created
Added Successfully
If you run this statement more than once, you'll get an error because the table already exists. To deal with that, here.
the easiest solution is to configure your database properties and make schema the same as user name but in capital litters
ex:
schema APP
user app
hope my answer can help.
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. :)