How to connect to mysql using eclipse running apache - java

I am creating a dynamic web project in eclipse. I have my local apache server running and configured with appropriate resource, mysql running and configured with the appropriate port.
I downloaded the appropriate driver, included it in the lib directory - I even tried adding it as an external JAR file to no avail. On the dynamic web page the result is "error connecting to database".
I created a JSP with the following code:
<%# page import="java.sql.*"%><%# page import="java.io.*"%><%# page import="com.mysql.*"%><?xml version="1.0"?>
<tours>
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jbdc:mysql://localhost:3306/tours", "root", "root");
out.println("connected to database!");
}
catch(SQLException e) {
out.print("error connecting to database");
}
%>
</tours>
Please advise...
Thanks in advance.

Put print after Class.forName() check, if that statement is not printing then problem is driver if that line is printing then problem is mysql database name problem or credential problem
If problem in drive then download from here :
http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
Problem is u put jbdc instead of jdbc
Code like this
<%
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
out.println("Driver is available !");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tours",
"root", "root");
out.println("connected to database!");
}
catch(SQLException e) {
out.print("error connecting to database");
}
%>

There are couple of things to take care of here.
1. Make sure that mysql is listening on port 3306.
2. Cross check the database name.
Lastly get the driver jar file in deployment assembly.
If the problem still persists, please print the stacktrace and post it here.

Please check weather your database is started or not i know it should be in comment but i cannot keep it in comment because i don't have sufficient reputations. please try it if it helps you it is fine.
How to start database is shown below:
Click Windows button+r then enter Services.msc in search bar then select Mysql and click start option

Printing the stack trace might help it could be because of authorization issue. If the error is related to authorization issue, you may have to change the server configurations.

Related

Why is this mySQL database not connecting to Netbeans?

The mysql database will not connect to the netbeans code. I am using a Mac Device and have installed mySQL on my device (it is running fine on localhost:8080). However, the connection through Java is not working. I believe there may be an error in the following line "conn = Driver Manager..." since it is not executing. I am unsure of how to change the password / what the password is.
Restarting Xampp
Screenshot of connection code
Expected result: user input is sent to mySQL database
Actual result (error): seen in this screenshot
This is the general database connectivity code .
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","MysqlUsername","MysqlPassword");
Statement stmt = (Statement) con.createStatement();
String query = "YourMysqlQuery";
stmt.executeUpdate(query);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
// You also have to add 'jdbc driver' in lib folder of your project.
If want us to solve the problem in your code then please provide the actual code you have done , Not the image .

Connection in Java to a Database

I'm working on OS X, Eclipse, Java 8 and MySQLWorkBench.
I realize with the last a database (can I say schema?), named "mydb" located at localhost:3306 (I don't know exactly what it means)...
Now I would like to connect via a java program to this db.
I'm trying with
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb");
It follows the error message
Exception in thread "main" java.sql.SQLException:
No suitable driver found for jdbc:mysql://localhost:3306/mydb
Can someone tell me what's wrong?
You need to download the jdbc driver and add it to your project
Download the driver from here
Example on how to add the driver in eclipse
Also you need to include the username and password in the connection statement and make sure you call the Class for name to get the driver loaded
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(DB_URL,USER,PASS);
You haven't added required library to connect java application with MySql database.you can download it form here.After once you get downloaded , just extract zip wherever you want.And add it into your project library folder.
Right click on project goto property -> java build path -> add external jar .
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","userName","userPass");
where userName is your database username and userPass is your password corresponding to that user.
After download and adding the Connector/J to your build path like #Jacques said.
Try this code:
try {
// Load the JDBC driver
#SuppressWarnings("rawtypes")
Class driver_class = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) driver_class.newInstance();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", getDbUser(), getDbPassword());
return conn;
} catch (Exception e) {
// TODO: handle exception
}
Where getDbUser() is your database username and getDbPassword() is your database password.

Connect to mysql remote database using JDBC?

I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dburl, userName, passWord);
Statement st = connection.createStatement();
String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
int rsI = st.executeUpdate(query);
System.out.println("Hi");
}catch (Exception e) {
System.out.println(e);
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
When I run this, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.The driver has not received any packets from the server.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/

Connect to DB (Derby)

I try to connect to the database with this code:
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url = "jdbc:derby://localhost:1527/sample";
Connection con = DriverManager.getConnection(url);
PreparedStatement pstmt=con.prepareStatement("insert into app.discount_code values('A',22)");
pstmt.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
..but not result. What do I need to do to connect to the DB?
Sir, You are connecting to derby network server. So you need to firstly config the environment and start the network server. Please also check the jdbc driver jars are correct.
About how to config and start derby network server.Look at here.
http://db.apache.org/derby/papers/DerbyTut/ns_intro.html#ns_config_env
Also you'd better put the close method in your finally block.
You'd better paste your error message, it wil be helpful to find your problem.

How to connect MySQL to Java program

I ve installed MySQL (last update).
I need to code, that ll create & establish a connection with SQL DB
& manage the DB(using SELECT, INSERT, CREATE).
I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).
Can anyone tell me wat is meant by URL in the below line?
Connection connection = DriverManager.getConnection(url, username, password);
I ve tried this:
String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
But it's not working. I am unable able to understand the term 'URL'.
Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.
Update:
This is the Full code. It still cannot connect.
import java.sql.*;
public class TestDriver {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection
System.out.println("Driver Loaded Succesfully");
}
catch (Exception e){
System.out.println("Unable to Load Driver!!!");
}
try {
Class.forName(com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
System.out.println("connection Established");
}
catch(Exception e) {
System.out.println("Couldnt get connection");
}
}
}
Can you tell me wat is the purpose of MySQL Connector/J?
In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.
If you are using a MySQL database:
Class.forName("com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:
Class.forName("net.sourceforge.jtds.jdbc.Driver"); // initialise the driver
String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";
Here's an extract from your code:
} catch (Exception e) {
System.out.println("Couldnt get connection");
}
You should never suppress exceptions as long as you don't understand its cause. Replace it by at least:
} catch (Exception e) {
System.out.println("Could not get connection");
e.printStackTrace();
}
Or maybe
} catch (Exception e) {
throw new RuntimeException("Could not get connection", e);
}
Either way, you should see the exception type, message and trace. In your code snippet the possible exceptions are ClassNotFoundException and SQLException. The first one would mean that the driver is not properly placed in the classpath. The second one would mean that connection cannot be obtained. The exception message and/or trace should tell in detail about the underlying root cause of the problem.
You should always observe exceptions. They tell something about the cause of the problem. You know, once a cause is understood, the solution is nothing more than obvious :)
See also:
Short MySQL/JDBC tutorial - Contains explanation about exception causes.
Further,
Can anyone tell me wat is meant by URL in the below line?
An URL is an Uniform Resource Locator. It's a common way to locate (identify) unique resources in computer systems and networks. The URL syntax for the MySQL database is explained in the documentation of the JDBC driver.
Can you tell me wat is the purpose of MySQL Connector/J?
It's the JDBC driver. The JDBC API exist of almost only interfaces. The DB vendors should provide their own concrete JDBC API implementation, which is the JDBC driver. With a JDBC driver you'll be able to connect a specific database using JDBC API.
If its MS SQL Server,
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
For more info, see this to get started with Microsoft JDBC.
You can use any of the two JDBC drivers for MSSQL:
Microsoft SQL Server JDBC Driver
2.0
jTDS
For MS SQL Server driver 2.0, use
URL: jdbc:sqlserver://server:port; DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
For MySql & Java, see this on SO.
You forgot a " at Class.forName(com.mysql.jdbc.Driver");
It should be
Class.forName("com.mysql.jdbc.Driver");

Categories