PDA

View Full Version : Connect to database in Java



Vistz
September 22nd, 2010, 07:19 PM
I have a website with a database set up. How would I connect to it using Java?

This is some code I found on another website


public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,pa ssword);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Do I need to change the "driver" variable to something else in order to get this to work?

kahumba
September 22nd, 2010, 08:21 PM
How would I connect to it using Java?
http://www.google.com/#sclient=psy&hl=en&q=Java+connect+to+mysql&aq=f&aqi=g4&aql=&oq=&gs_rfai=&pbx=1&fp=6f32b8af52b7e0b8

Vistz
September 22nd, 2010, 10:38 PM
import java.sql.*;

public class Connect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "mysql15.000webhost.com/";//I replaced this with my host name
String dbName = "a2609916_hscore";//name of database
String driver = "com.mysql.jdbc.Driver";//I left this as is
String userName = "root"; //mysql user name
String password = "root";//password
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,pa ssword);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I run the code above, I get an error,

java.sql.SQLException: No suitable driver found for mysql15.000webhost.com/a2609916_hscore

Some Penguin
September 22nd, 2010, 11:07 PM
You haven't said whether you've downloaded an appropriate MySQL JDBC connector and placed the .jar in your classpath.

Vistz
September 23rd, 2010, 02:07 AM
You haven't said whether you've downloaded an appropriate MySQL JDBC connector and placed the .jar in your classpath.

I've run this


sudo apt-get install libmysql-java

And I've placed "mysql-connector-java-5.1.10.jar" in my classpath"

wkhasintha
September 23rd, 2010, 07:21 AM
Make sure the jdbc driver is in the class path.

Some Penguin
September 23rd, 2010, 08:10 AM
It's also important to not omit the jdbc:mysql part of the URI.

Vistz
September 23rd, 2010, 03:08 PM
I still get an error even after I change the url


String url = "jdbc:mysql//mysql15.000webhost.com/";

r-senior
September 23rd, 2010, 05:33 PM
Your URL should look more like this:


jdbc:mysql://hostname:3306/databasename

3306 is the default port for MySQL but you might want to verify that's correct in your case.