Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to install JDBC and how to use it to connect to mysql?

Tags:

java

jdbc

i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?

below is the codes that i used

import java.sql.*;
public class Test1
{
    public static void main (String[] args)
    {
        String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
        String username = "root";
        String password = "ma";
        Connection connection = null;
        try {
            System.out.println("Connecting database...");
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("Database connected!");
        } catch (SQLException e) {
            System.err.println("Cannot connect the database!");
            e.printStackTrace();
        } finally {
            System.out.println("Closing the connection.");
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ignore) {

                }
            }
        }
    }
}

And below is the Response that i get

Cannot connect to database server

Update # 3

C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at Test1.main(Test1.java:12)
Closing the connection.
like image 850
Mahmoud Avatar asked Jul 05 '10 21:07

Mahmoud


People also ask

How does JDBC connect to MySQL?

Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name.

Does JDBC work with MySQL?

In Java, we can connect to our database(MySQL) with JDBC(Java Database Connectivity) through the Java code. JDBC is one of the standard APIs for database connectivity, using it we can easily run our query, statement, and also fetch data from the database.


1 Answers

You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.

You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial

like image 143
BalusC Avatar answered Nov 14 '22 23:11

BalusC