This article illustrates the Java database implementation method using JDBC, which is a very practical and important technique in Java data design. Share to everyone for your reference. Specifically as follows:
JDBC (Java Data Base Connectivity) database connection, we usually use JDBC when writing a Web application or Java application to connect to a database. To connect to a database using JDBC The general steps are:
1. Load Driver
2. Create a Connection object
Connection con = drivermanager.getconnection (Url,username,password);
3. Create SQL statement Execution object
4. Execute SQL statement
5, the implementation of the results of processing
6. Close related connection objects (in reverse order of declaration)
The following is an example of a connection to a MySQL database in which the process of other databases is similar:
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement; public class DbConnection {public static void main (string[] args) {String driver = "Com.mysql.jdbc.Driver";//localhost refers to
This machine can also be replaced with local IP address, 3306 is the default port number for MySQL database, "user" is the database name String URL to be connected = "Jdbc:mysql://localhost:3306/user";
Fill in the database username and password String username = "Test";
String password = "Test"; String sql = "SELECT * from user";/write the SQL statement to execute where you query all users from the user table for information try {class.forname (driver);//Load driver. This uses the method of implicitly registering the driver} catch (ClassNotFoundException e) {e.printstacktrace ();} try {Connection con = drivermanager.getconnect Ion (Url,username,password)//Create Connection object Statement st = Con.createstatement ();//Create SQL Execution object ResultSet rs = St.executequery (
SQL)//executes the SQL statement and returns the result set while (Rs.next ())//To the result set traversal output {System.out.println ("Username:" +rs.getstring (1));//Get data by the label of the column System.out.println ("Useradd:" +rs.getstring ("Useradd"));//Get Data System.out.println by column name ("Userage:" +rs.getint("Userage")); ///Close Related object if (rs!= null) {try {rs.close ();} catch (SQLException e) {e.printstacktrace ();}} if (St!= null) {try {s
T.close ();
catch (SQLException e) {e.printstacktrace ();}}
if (Con!=null) {try {con.close ();} catch (SQLException e) {e.printstacktrace ();}}}
catch (SQLException e) {e.printstacktrace ();}} }
I believe that this article describes the Java database Program design has some reference value.