Java connection mysql database code sharing

 

This article mainly introduces the Java connection MySQL database code example program. The article introduces it in great detail through the example code. It has certain reference learning value for everyone's study or work. Friends who need it can refer to it.

Example of connecting to mysql using java

When connecting, first ensure that mysql is installed on the local machine or mysql is installed on the server.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class MainSql {

  // JDBC 驱动名及数据库 URL

  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

  static final String DB_URL = "jdbc:mysql://localhost:3306/chat";

  

  // 数据库的用户名与密码,需要根据自己的设置

  static final String USER = "root";

  static final String PASS = "";

  public static void main(String[] args) {

    // TODO Auto-generated method stub

    Connection conn = null;

    Statement stmt = null;

    try{

      Class.forName(JDBC_DRIVER);

      System.out.println("链接数据库..");

      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      stmt = conn.createStatement();

      String sql = "SELECT * FROM users";

      ResultSet rs = stmt.executeQuery(sql);

      while(rs.next()){

        // 通过字段检索

        String id = rs.getString("id");

        String password = rs.getString("passwd");

   

        // 输出数据

        System.out.println("用户名: " + id);

        System.out.println("密码: " + password);

      }

      rs.close();

      stmt.close();

      conn.close();

    }catch(SQLException se){

      // 处理 JDBC 错误

      se.printStackTrace();

    }catch(Exception e){

      // 处理 Class.forName 错误

      e.printStackTrace();

    }finally{

      // 关闭资源

      try{

        if(stmt!=null) stmt.close();

      }catch(SQLException se2){

      }// 什么都不做

      try{

        if(conn!=null) conn.close();

      }catch(SQLException se){

        se.printStackTrace();

      }

    }

    System.out.println("Goodbye!");

  }

}

This is the example program of mysql connection. Here I only pasted the code for calling mysql and bingqie from java to establish the connection. The sql statement is not called. The other parts can be found online.

The above is the entire content of this article, I hope it will be helpful to everyone’s study!

Reprinted from: Weidian Reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131816041