How Java connects to SQL drivers

Source: Internet
Author: User
Tags postgresql stmt

Some JDBC jar files will automatically register the drive class. The jar file containing the Meta-inf/services/java.sql.driver file can automatically register the drive class, and the driver jar file can be extracted to check if it contains the file.

If the driver jar file does not support autoenrollment, then you need to find out the name of the JDBC Drive class used by the database provider. The typical drive name is as follows:

Org.apache.derby.jdbc.ClientDriver

Org.postgresql.Driver

Com.mysql.jdbc.Driver

Another important note is the database URL, which we must use for various parameters related to the database type, such as hostname, port number, and database name.

JDBC uses a syntax similar to normal URLs to describe a data source.

The format is as follows:

Jdbc:subprotocol:other Stuff

Examples are as follows

Jdbc:derby://localhost:1527/corejava;create=true

Jdbc:mysql://localhost:3306/corejava

Jdbc:postgresql:COREJAVA

By using DriverManager, you can register the drive in two ways.

First, "Add External JARs" is required in project build path, adding C:\Program Files (x86) \mysql\mysql Connector J Directory of Mysql-connector-java-5.1.37-bin.jar (the goods are too TM hard to find it)

1. Load the drive class in the Java program, for example:

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

This statement will cause the drive class to be loaded, thus executing a static initializer that can register the drive class.

An example is as follows:

$ mysql-u root-p  Password:password

Database Creation statement:

CREATE DATABASE SONGCI;  Use SONGCI; CREATE TABLE INT, first_name varchr (varchar (+));

and insert some data.

--------------------------------------------------------------------------------------------------------------- --------------------------------------

The Java code snippet is as follows:

1  PackageCom.coresql.sqljdbc;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 ImportJava.sql.ResultSet;6 Importjava.sql.Statement;7 8  Public classMYSQLJDBC {9     Ten     Static { One         Try { AClass.forName ("Com.mysql.jdbc.Driver"); -}Catch(Exception e) { -System.out.println ("Error Loading MySQL driver!"); the e.printstacktrace (); -         } -     } -      +      Public Static voidMain (string[] args) { -         Try { +              AConnection connect =Drivermanager.getconnection ( at"Jdbc:mysql://localhost:3306/songci", "root", "MyPassword"); - //connection URL is jdbc:mysql//server address/database name, the following 2 parameters are login username and password, respectively -              -System.out.println ("Success Connect Mysql server!"); -Statement stmt =connect.createstatement (); -ResultSet rs = stmt.executequery ("SELECT * FROM Authors"); in              -              while(Rs.next ()) { toSystem.out.println (rs.getstring ("last_name") + "" + rs.getstring ("first_name")); +             } -}Catch(Exception e) { the e.printstacktrace (); *         } $     }Panax Notoginseng}

2. Another way is to set the Jdbc.driver property. You can specify this property with command-line arguments. For example:

$ java-djdbc.drivers=org.postgresql.driver ProgramName

Or use the following call to set system properties in your app

System.setproperty ("Jdbc.drivers", "Org.postgresql.Driver");

This method can be used to provide multiple drives, separated by a colon, for example:

Org.postgresql.Driver:org.apache.derby.jdbc.ClientDriver

The code for connecting to a database in a Java program is as follows:

String url = "Jdbc:postgresql:COREJAVA"= "root"= "MyPassword"= Drivermanager.getconnection (URL, username, password);

You can do this: load the connection parameters from a file named Database.properties and connect to the database.

Jdbc.drivers=com.jdbc.mysql.driver
Jdbc.url=jdbc:mysql://localhost:3306/songci
Jdbc.username=root
Jdbc.password=mypassword

The Java code is as follows:

1  Packagecom.testsql.getconnection;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 ImportJava.nio.file.Files;6 Importjava.nio.file.Paths;7 Importjava.sql.Connection;8 ImportJava.sql.DriverManager;9 ImportJava.sql.ResultSet;Ten Importjava.sql.SQLException; One Importjava.sql.Statement; A Importjava.util.Properties; -  -  Public classTestDB { the  -      Public Static voidMain (string[] args)throwsIOException { -         Try { - runtest (); +}Catch(SQLException e) { -              for(Throwable t:e) { + t.printstacktrace (); A             } at         } -     } -  -      -      Public Static voidRuntest ()throwsSQLException, IOException { -         Try(Connection conn =getconnection ()) { inStatement stat =conn.createstatement (); -ResultSet rs = stat.executequery ("SELECT * FROM Authors"); to              +              while(Rs.next ()) { -System.out.println (rs.getstring ("last_name") + "" + rs.getstring ("first_name")); the             } *System.out.println ("Done"); $         }Panax Notoginseng     } -      the      Public StaticConnection getconnection ()throwsSQLException, IOException { +Properties props =NewProperties (); A          the         Try(InputStream in = Files.newinputstream (Paths.get ("Database.properties"))) { + props.load (in); -         } $          $String drivers = Props.getproperty ("Jdbc.drivers"); -         if(Drivers! =NULL) { -System.setproperty ("Jdbc.drivers", drivers); the         }         -         WuyiString url = props.getproperty ("Jdbc.url"); theString user = Props.getproperty ("Jdbc.username"); -String Password = props.getproperty ("Jdbc.password"); Wu          -         returndrivermanager.getconnection (URL, user, password); About     } $}

Execute the SQL statement in the code:

Before executing the SQL command, you first need to create a statement object. To create a statement object, you need to use the connection object obtained by invoking the Drivermanager.getconnection method.

Statement stat = conn.createstatement ();

The SQL statement that will be executed is then put into the string, for example:

String command = "UPDATE Books"      + "SET price=price-5.00"      + "WHERE Title not like '%introduction% '";

Then call:

Stat.executeupdate (command);

The Executeupdate method returns the number of rows affected by the SQL command. This method can also execute data definition statements such as CREATE table and drop table for operations such as INSERT, UPDATE, and delete in SQL

When you perform a query operation, the ExecuteQuery method is used to return an object of type resultset.

ResultSet rs = stat.executequery ("SELECT * from Books");

You can usually use a looping statement similar to the following when analyzing the results:

 while (Rs.next ()) {    // look at a row of result set}

How Java connects to SQL drivers

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.