Java connects to the Mysql database through JDBC

  • 2020-04-01 04:21:01
  • OfStack

JDBC (Java Data Base Connectivity) is a Java API for executing SQL statements that provides unified access to multiple relational databases. It consists of a set of classes and interfaces written in the Java language. JDBC provides a benchmark against which more advanced tools and interfaces can be built, enabling database developers to write database applications.

If you want to use the database to add the database driver, different databases have different drivers, not here, add jar program driver package method is not explained here,

Another article has an introduction (link: #)

The following is an example of how to connect to a mysql database.


import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class MysqlDemo {
  public static void main(String[] args) throws Exception {
    Connection conn = null;
    String sql;
    // MySQL the JDBC URL Writing method: jdbc:mysql:// Host name: connection port / Database name ? parameter = value 
    //Avoid Chinese garble to specify useUnicode and characterEncoding
    //Before performing a database operation, create a database on the database management system with a name of your own.
    //Create the javademo database before the following statement
    String url = "jdbc:mysql://localhost:3306/javademo?"
        + "user=root&password=root&useUnicode=true&characterEncoding=UTF8";
    try {
      //The reason for using the following statement is that we are using a MySQL driver, so we are going to drive it,
      //You can load it in with class.forname, or you can drive it with initialization, all three of the following
      Class.forName("com.mysql.jdbc.Driver");//Load the mysql driver dynamically
      // or:
      // com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
      // or : 
      // new com.mysql.jdbc.Driver();
      System.out.println(" Successfully loaded MySQL The driver ");
      //A Connection represents a database Connection
      conn = DriverManager.getConnection(url);
      //The Statement comes with a number of methods, such as executeUpdate, that implement inserts, updates, and deletions
      Statement stmt = conn.createStatement();
      sql = "create table student(NO char(20),name varchar(20),primary key(NO))";
      int result = stmt.executeUpdate(sql);//The executeUpdate statement returns an affected number of rows, and if -1 is returned, it fails
      if (result != -1) {
        System.out.println(" The data table was created successfully ");
        sql = "insert into student(NO,name) values('2012001',' TaoWeiJi ')";
        result = stmt.executeUpdate(sql);
        sql = "insert into student(NO,name) values('2012002',' Zhou Xiaojun ')";
        result = stmt.executeUpdate(sql);
        sql = "select * from student";
        ResultSet rs = stmt.executeQuery(sql);//ExecuteQuery returns a collection of results, or a null value
        System.out.println(" Student id t The name ");
        while (rs.next()) {
          System.out
              .println(rs.getString(1) + "t" + rs.getString(2));//GetInt () if you return an int
        }
      }
    } catch (SQLException e) {
      System.out.println("MySQL The operating error ");
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      conn.close();
    }
  }
}

Also attached are methods for JDBC connections to various databases (classic)

1) connect Oracle 8/8i/9i/10g/11g (thin mode)


Class.forName("oracle.JDBC.driver.OracleDriver").newInstance();

String url="JDBC:oracle:thin:@localhost:1521:orcl"    //Orcl is the SID of the Oracle database

String user="test";

String password="test";

Connection con=DriverManager.getConnection(url,user,password);

2) connect to the DB2 database


Class.forName("com.ibm.db2.jcc.DB2Driver");

String url="JDBC:db2://localhost:5000/testDb";

String user="test"; String password="test";

Connection con=DriverManager.getConnection(url,user,password);

3) connect to MySQL database


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

String url="JDBC:mysql://localhost:8080/testDB";

String user="test"; String password="test";

Connection con=DriverManager.getConnection(url,user,password);

4) connect to SQL Server2000 database


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

String url="JDBC:microsoft:sqlserver://localhost:1433;DatabaseName=testDb";

String user="test"; String password="test";

Connection con=DriverManager.getConnection(url,user,password);

5) connect to the PostgreSQL database


Class.forName("org.postgresql.Driver");

String url="JDBC:postgresql://localhost/testDb";

String user="test"; String password="test";

Connection con=DriverManager.getConnection(url,user,password);

6) connect to the Access database

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="JDBC:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/testDb/mdb");
Connection conn=DriverManager.getConnection(url,"","");

Connect to the Sybase database


Class.forName("com.sybase.JDBC.SybDriver");

String url="JDBC:sybase:Tds:localhost:5007/testDb";

Properties pro=System.getProperties();

pro.put("user","userId");

pro.put("password","user_password");

Connection con=DriverManager.getConnection(url,pro);

Connect to informix database

Class.forName("com.informix.JDBC.ifxDriver");
String url="JDBC:informix-sqli:localhost:1533/testDb:INFORMIXSERVER=myserver"user=testUser;password=testpassword"; Connection con=DriverManager.getConnection(url);


Related articles: