JDBC (Java Data Base Connectivity) database connection, we use JDBC when writing a Web application or Java application to connect to a database. Using JDBC to connect to a database The general steps are:
1, load driver Class.forName (driver);
2. Create Connection object Connection con = drivermanager.getconnection (Url,username,password);
3. Create SQL statement Execution object
4. Execute SQL statements
5, the implementation of the results of processing
6. Close related connection objects (in reverse order of declaration)
The following is an example of establishing a connection to a MySQL database, and 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 the machine, you can also use local IP address, 3306 is the default port number of MySQL database, "user" is the name of the database to connect
String url = "Jdbc:mysql://localhost:3306/user";
Fill in the database username and password
String username = "Test";
String password = "Test";
String sql = "SELECT * from user";//writes the SQL statement to be executed, where information is queried from the user table for all users
Try
{
Class.forName (driver);//Load driver, the method used to implicitly register the driver here
}
catch (ClassNotFoundException e)
{
E.printstacktrace ();
}
Try
{
Connection con = drivermanager.getconnection (Url,username,password);//Create Connection object
Statement st = Con.createstatement ();//Create SQL Execution Object
ResultSet rs = st.executequery (sql);//Execute SQL statement and return result set
while (Rs.next ())//traversal output for result set
{
System.out.println ("Username:" +rs.getstring (1));//Use the label of the column to get the data
System.out.println ("Useradd:" +rs.getstring ("Useradd"));//Get Data by column name
System.out.println ("Userage:" +rs.getint ("Userage"));
}
Close the related object
if (rs! = null)
{
Try
{
Rs.close ();
}
catch (SQLException e)
{
E.printstacktrace ();
}
}
if (st! = NULL)
{
Try
{
St.close ();
}
catch (SQLException e)
{
E.printstacktrace ();
}
}
if (Con!=null)
{
Try
{
Con.close ();
}
catch (SQLException e)
{
E.printstacktrace ();
}
}
}
catch (SQLException e)
{
E.printstacktrace ();
}
}
}