Java and database connection methods

Source: Internet
Author: User
Tags getmessage informix odbc postgresql readline sybase sybase database microsoft website

There are two main ways to connect a database with Java, one is to connect with the Jdbc-odbc bridge, the other is to connect with the corresponding driver provided by the manufacturer, first of all to talk about the first connection.

The JDBC-ODBC bridge is implemented using Jdbcodbc.class and a local library for accessing ODBC drivers. For Windows platforms, this local library is a dynamic connection library DLL

(JDBCODBC. DLL).

Because JDBC is designed to be very close to ODBC. Internally, the driver maps the JDBC method to an ODBC call, so that JDBC can be used with any available ODBC driver

Interact with. The advantage of this bridge is that it gives JDBC the ability to access almost all databases at present. The prevailing mode is as shown in the figure:

Application---JDBC API---JDBC-ODBC---ODBC API---ODBC Layer---data source

The specific methods are:

First open the Control Panel management tool, open the data source (ODBC), and add the data source (i.e. the name of the database you are connecting to) to the User DSN, where you assume that you are connecting to SQL SERVER

2000 of the Goodssupply database. Name fill in the name of the database you want to connect to (goodssupply), and then step through the settings, if you choose to use the Sql-server password authentication,

You must enter the appropriate username and password to connect to the database. All the way to the next setup complete.

In Java to write programs to test, where my program is to allow users to enter any table name and the name of the column, the column of all data output. The source code is as follows:

Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import java.sql.*;

public class Odbcbridge {

public static void Main (string[] args) {
String url= "Jdbc:odbc:GoodsSupply";
Statement Sm=null;
String Command=null;
ResultSet Rs=null;
String Tablename=null;
String Cname=null;
String Result=null;
BufferedReader input=new BufferedReader (New InputStreamReader (system.in));
try {
try {
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver"); Load Driver
}catch (ClassNotFoundException e) {
System.out.println ("Can not load Jdbc-odbc bridge Driver");
System.err.print ("ClassNotFoundException:");
System.err.println (E.getmessage ());
}
Connection con=drivermanager.getconnection (URL, "USER", "PASSWORD"); Using SQL-SERVER2000 Certification
DatabaseMetaData Dmd=con.getmetadata (); DMD for the corresponding condition of the connection
SYSTEM.OUT.PRINTLN ("Connected Database:" +dmd.geturl ());
System.out.println ("Driver:" +dmd.getdrivername ());
Sm=con.createstatement ();
SYSTEM.OUT.PRINTLN ("Input table name");
Tablename=input.readline ();
while (true) {
System.out.println ("Enter column name (end of NULL program):");
Cname=input.readline ();
if (Cname.equalsignorecase (""))
Break
command= "Select" +cname+ "from" +tablename;
Rs=sm.executequery (command); Execute Query
if (!rs.next ())
SYSTEM.OUT.PRINTLN ("Wrong table name or column name entered incorrectly");
else {
SYSTEM.OUT.PRINTLN ("Query result is:");
Todo
{
Result=rs.getstring (CName);
The database language is set to Chinese without converting the encoding
Result=new String (result.getbytes ("iso-8859-1"), "GB2312");
SYSTEM.OUT.PRINTLN (result);
}while (Rs.next ());
}
}
}catch (SQLException ex) {
System.out.println ("SQLException:");
while (Ex!=null) {
SYSTEM.OUT.PRINTLN ("Message:" +ex.getmessage ());
Ex=ex.getnextexception ();
}
}catch (Exception e) {
System.out.println ("IOException");
}
}
}


Java and Database connection methods (ii)

Now introduce the second method, which is connected by the corresponding driver provided by the vendor.

This is done directly by using a driver created with a dedicated network protocol provided by the database vendor, which translates the JDBC API call directly into a direct network call. This adjustment

The general performance of the method is relatively good, but also the simplest way of practical. Because it is necessary to install additional libraries or middleware. Almost all of the database vendors provide their databases

This database provides this JDBC driver, or it can be obtained from third-party vendors.

From the URL http://industry.Java.sun.com/products/jdbc/drivers/you can see a list of all the useful drivers. The result is as shown in the figure:

Application---JDBC API---driver---data source

First of all, install JDBC driver, recommend SP2 version, can download from Microsoft website
http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&DisplayLang=en Download the bottom of the

SETUP. Exe

This driver should match the SQL SERVER2000 SP3a, the corresponding download URL is
http://www.microsoft.com/china/sql/downloads/sp3.asp Download Chs_sql2ksp3.exe

If you compile directly with the Java SDK, you need to set the environment variables to set the Lib three files in the installed JDBC driver as environment variables:
Classpath
D:\program Files\Microsoft SQL Server\jdbc\lib\msbase.jar;
D:\program Files\Microsoft SQL Server\jdbc\lib\mssqlserver.jar;
D:\program Files\Microsoft SQL Server\jdbc\lib\msutil.jar;

Installation can use Microsoft's driver to connect to the database, the corresponding code is basically the same as before:

Import java.sql.*;
Import java.io.*;
public class DbColumn {

public static void Main (string[] args) {
Connection Con=null;
Statement Sm=null;
String Command=null;
ResultSet Rs=null;
String Tablename=null;
String Cname=null;
String Result=null;
BufferedReader input=new BufferedReader (New InputStreamReader (system.in));
Try
{
Class.forName ("Com.microsoft.jdbc.sqlserver.SQLServerDriver");
SYSTEM.OUT.PRINTLN ("Driver Loaded");
SQL Server login must be logged in using SQL Server password authentication method
Con=drivermanager.getconnection ("jdbc:microsoft:sqlserver://servername:1433", "USER", "PASSWORD");
Con.setcatalog ("goodssupply");
System.out.println ("OK, connect to database successfully");
}catch (Exception ex) {
Ex.printstacktrace ();
}
Try
{
Sm=con.createstatement ();
SYSTEM.OUT.PRINTLN ("Input table name");
Tablename=input.readline ();
while (true) {
System.out.println ("Enter column name (end of NULL program):");
Cname=input.readline ();
if (Cname.equalsignorecase (""))
Break
command= "Select" +cname+ "from" +tablename;
Rs=sm.executequery (command);
if (!rs.next ())
SYSTEM.OUT.PRINTLN ("Wrong table name or column name entered incorrectly");
else {
SYSTEM.OUT.PRINTLN ("Query result is:");
Todo
{
Result=rs.getstring (CName);
Result=new String (result.getbytes ("iso-8859-1"), "GB2312");
SYSTEM.OUT.PRINTLN (result);
}while (Rs.next ());
}
}
}catch (Exception ex) {
Ex.printstacktrace ();
}
}
}


Java and database connection methods (iii)

Finally give the Java connection to other database key code:

1, oracle8/8i/9i database (thin mode)
Class.forName ("Oracle.jdbc.driver.OracleDriver"). newinstance ();
String url= "Jdbc:oracle:thin: @localhost: 1521:ORCL";
ORCL is the SID of the database
String user= "Test";
String password= "Test";
Connection conn= drivermanager.getconnection (Url,user,password);

2. DB2 Database
Class.forName ("Com.ibm.db2.jdbc.app.DB2Driver"). newinstance ();
String url= "Jdbc:db2://localhost:5000/sample";
Sample for your database name
String user= "admin";
String password= "";
Connection conn=drivermanager.getconnection (Url,user,password);

3. Sybase database
Class.forName ("Com.sybase.jdbc.SybDriver"). newinstance ();
String url = "Jdbc:sybase:tds:localhost:5007/mydb";
MyDB for your database name
Properties sysprops = System.getproperties ();
Sysprops.put ("User", "userid");
Sysprops.put ("Password", "User_password");
Connection conn= drivermanager.getconnection (URL, sysprops);

4. Informix Database
Class.forName ("Com.informix.jdbc.IfxDriver"). newinstance ();
String URL =
"Jdbc:informix-sqli://123.45.67.89:1533/mydb:informixserver=myserver;
User=testuser;password=testpassword ";
MyDB for Database name
Connection conn= drivermanager.getconnection (URL);

5. mysql Database
Class.forName ("Org.gjt.mm.mysql.Driver"). newinstance ();
String url = "jdbc:mysql://localhost/mydb?user=soft&password=soft1234&useunicode=
True&characterencoding=8859_1 "
MyDB for Database name
Connection conn= drivermanager.getconnection (URL);

6. PostgreSQL Database
Class.forName ("Org.postgresql.Driver"). newinstance ();
String url = "Jdbc:postgresql://localhost/mydb"
MyDB for Database name
String user= "MyUser";
String password= "MyPassword";
Connection conn= drivermanager.getconnection (Url,user,password);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.