The method of connecting a Java program to a database

  • 2020-04-01 04:14:38
  • OfStack

A network relational database application system is a three - level structure. The client and server are connected by network, and the client side application communicates with the server side database program according to the communication protocol. The database service program communicates with the database management system through SQL commands.

There are two ways to connect a Java program to a database. One is to use jdbc-odbc bridge to connect to the database, and the other is to use a pure Java JDBC driver to connect to the database.
Connect to the database using the jdbc-odbc bridge

The Java program USES the jdbc-odbc bridge to connect to the database. The communication process between the Java program and the database is:
First, the database application makes the API call to the ODBC driver manager, which converts the call to the ODBC driver call to the database management system, which converts the call to the data input/output call to the operating system. Finally, the operating system returns the actual data level by level from the database.

The first step of database programming is to set up the data source. The steps of setting up the data source in ODBC are as follows:
Open the administration tool in the Windows control panel. For Windows XP: select "performance maintenance" > > "Management tools" > > "Data source (ODBC)"; For Windows 2000: choose management tools > > Data source.
Open data sources. The ODBC data source manager dialog box appears, showing the existing data source names.
Select user DSN, click the add button, and the install data source driver dialog box appears. Access(*.mdb) data source, click finish, the create data source dialog box appears, type the name of the data source you want to create, and select a database table for the created data source.
Click the select button in the database area to select the desired database table. When you need to authorize access levels for the data source, click the advanced button. After setting the login name and password, click ok to complete the configuration of the Access database in ODBC administrator.
If you do not already have a database table, you need to create one.

The data source is the database, on the basis of setting the data source, the Java program to access the database table, but also establish jdbc-odbc bridge, let the program and the database connection. Later, the program can send SQL statements to the database to process the results returned by the database. Java DataBase Connectivity consists of a set of classes and interfaces written in the Java language. JDBC is the Java program and DataBase connection API. It can do three things: establish a connection to a database, send an SQL statement to the database, and process the results returned by the database.

Calling the Class method class.forname (String s) establishes the jdbc-odbc bridge. For example, the code:


  try{
    Class.forName( " sun.jdbc.odbc.JdbcOdbcDriver " );
  }catch(Exception e){}


The driver is loaded for the Java program.
ConnectByJdbcOdbc (), which connects to the database with a given database URL, username, and password. If the connection is successful, the method returns the connection object. If the connection is unsuccessful, it returns nothing.


public static connection connectByjdbcOdbc(String url, String username, String password){
  Connection con = null;
  try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  //Load the ODBC driver
  }
  catch (Exception e){
    e.printStackTrace();
    return null; //The connection fails
  }
  try{
    con = DriverManager.getConnection(url, username, password);
  }
  catch (SQLExceotuib e){
    e.printStackTrace();
    return null; //Connection not successful
  }
  return con; //The connection is successful
}

The following code is a call to the connectByJdbcOdbc() method. If the database connection is successful, the database connection window will pop up. Otherwise, the database connection window will pop up.


if ((con = connectByJdbcOdbc("jdbc:odbc:redsun", "xia", "1234")) != null){
  JoptionPane.showMessageDialog(null, " Database connection successful ");
  try{
    con.close();
    con = null;
  }
  catch (SOLException e){}
}
else
  JOptionPane.showMessageDialog(null, " Database connection failed ");

Connect to the database with a pure Java JDBC driver

Java programs can also connect to a database using a pure Java JDBC driver. This method is more widely used, but you need to download the corresponding driver package, because different databases may have different connection codes, connect to different databases, and load different drivers. Connection, for example, essentially a driver on the www.msdn.com website to download, there are three packages: msbase. Jar, mssqlserver. Jar and msutil jar, and asked the three bags in JDK \ jre \ lib \ ext \ directory, or placed in the CLASSPATH setting its position.

Using a pure Java JDBC driver to connect to the database is as follows:
Load the driver. There are two ways to load a driver:
One is to add the driver to the attribute jdbc.drivers of java.lang.system. This is a list of DriverManager classloading driver class names, separated by colons.
Another way is to load the specified driver in the program using the class.forname () method after downloading the driver from the relevant web site. Such as:


  Class.forName( " com.microsoft.jdbc.sqlserver.SQLServerDriver " );


Creates the URL for the specified database. The URL object of the database is similar to the uniform resource locator of the network, whose format is:


  jdbc:subProtocol:subName://hostname:port:Databasename=XXX


Among them, subprotocol is a database connection mechanism supported by a driver. SubName is the concrete name under the current connection mechanism; HostName is the hostName; Port is the corresponding connection port; DatabaseName is the name of the database to connect to. For example, the following code could be the URL of a database:


  jdbc:Microsoft:sqlserver://localhost:1433;Databasename=ksinfo


The URL description of the database USES the mechanism provided by miscrosoft to use sqlserve driver to access the ksInfo database on the local machine through port 1433.
Establish connections. The method getConnection() for DriverManager establishes a connection.

ConnectByJdbc (), a static method that connects to a database with a given database URL, username, and password, returns true if the connection is successful, or false if the connection is unsuccessful.


public static Connection conectByJdbc(String url, String username, String password){
  Connection con = null;
  try{
    Class.forName( //Load a specific driver
    "com.microsoft.jdbc.sqlserver.SQLServerDriver");
  }
  catch (Exception e){
    e.printStackTrace();
    return null; //The connection fails
  }
  try{
    con = DriverManage.getConnection(url, username, password);
  }
  catch (SQLException e){
    e.printStackTrace();
    return null; //The connection fails
  }
  return con; //The connection is successful
}


Related articles: