How to make database connectivity in Java using JD

2019-06-05 01:03发布

问题:

How to create a jdbc connection in Java?

回答1:

To create a connection, you need to load the driver first. For example, for MySQL:

Class.forName("com.mysql.jdbc.Driver");

The driver class to load obviously depends on the JDBC driver (and thus on the database) that needs to be on the classpath.

Then, make the connection:

String url = "jdbc:mysql://host_name:port/dbname";
String user = "scott";
String pwd = "tiger";
Connection con = DriverManager.getConnection(url, user, pwd);

The url is the "connection url" and identifies the database to connect to. Again, the syntax will depend on the JDBC driver you're using. So, refer to the documentation of your JDBC driver.

Establishing a Connection in The Java Tutorials is indeed a good reference.



回答2:

See sun's jdbc tutorial for begginers

Particularly http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html

First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC™ application connects to a target data source using one of two mechanisms:

DriverManager: This fully implemented class requires an application to load a specific driver, using a hardcoded URL. As part of its initialization, the DriverManager class attempts to load the driver classes referenced in the jdbc.drivers system property. This allows you to customize the JDBC Drivers used by your applications.

DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.

Connection con = DriverManager.getConnection
           ( "jdbc:myDriver:wombat", "myLogin","myPassword");


回答3:

Have a look at ABCs of JDBC.



回答4:

To create a jdbc connection in java , you need to know about some classes and interfaces required to establish a connection which are provided in java.sql package.

Classes are Drivermanager and Types.

Interfaces are Connection, Statement, PreparedStatement, CallableStatement, ResultSet...etc

This is the program to establish a jdbc connection

import java.sql.*;
class Sssm
{
public static void main(String aaa[])throws SqlException
{
Drivermanager d=new oracle.jdbc.driver.OracleDriver();
DriverManager.getconnection(d);
Connection c=Drivermanager.getconnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
c.close();
}
}

Note : Instead of scott and tiger.. please write the login credentials that you have provided for oracle database.



标签: java jdbc