1、虚拟机安装mySQL 服务器, 宿主机分别使用navicat工具和java代码 访问mySQL,组网图如下:

      编程实践:使用java访问mySQL数据库

2. 查看mySQL的服务器状态,如下:

    编程实践:使用java访问mySQL数据库

3. 服务器上查看数据库和数据表内容如下:

   编程实践:使用java访问mySQL数据库

 

4. 在宿主机上,使用navicat 查看内容如下:

   编程实践:使用java访问mySQL数据库

编程实践:使用java访问mySQL数据库

查看user数据表中的内容,如下,其实有很多列,下面只是一个截图,从截图结果看,已经可以看出有6行记录,此结果与服务器上看到的记录内容是相同的。

编程实践:使用java访问mySQL数据库

5. 在宿主机上,使用java 代码查看数据库内容,java代码如下:

 1 /*
 2  * To change this license header, choose License Headers in Project Properties.
 3  * To change this template file, choose Tools | Templates
 4  * and open the template in the editor.
 5  */
 6 
 7 package sequensesearch;
 8 import java.sql.*;
 9 
10 /**
11  *
12  * @author zhou
13  */
14 public class SequenseSearch {
15 
16     /**
17      * @param args the command line arguments
18      */
19     public static void main(String[] args) {
20         Connection con=null;
21         Statement sql;
22         ResultSet rs;
23         
24         try { Class.forName("com.mysql.jdbc.Driver");
25         }        
26         catch(Exception e) {}
27         
28         String uri = "jdbc:mysql://192.168.248.156:3306/mysql?useSSL=false";
29         String user = "root";
30         String password = "123456";
31         try {
32             //与数据库建立连接
33             con = DriverManager.getConnection(uri, user, password);
34         }
35         catch(SQLException e) {}
36         
37         try{
38             //创建一个SQL语句对象
39             sql = con.createStatement();
40             rs = sql.executeQuery("SELECT user, host FROM user");
41             //执行查询
42             //rs = sql.executeQuery("SELECT * FROM student");            
43             while(rs.next())
44             {
45                 String users = rs.getString(1);
46                 String host   = rs.getString(2);
47                 
48                 System.out.printf("%s\t", users);
49                 System.out.printf("%s\t", host);
50                 System.out.printf("\n");
51             }
52             
53             con.close();
54         }            
55         catch(SQLException e){
56             System.out.println(e);
57         }   
58     }
59 }
java代码访问mySQL

相关文章:

  • 2021-06-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2022-01-15
  • 2021-09-08
  • 2022-01-28
猜你喜欢
  • 2022-12-23
  • 2022-01-06
  • 2021-11-17
  • 2022-01-31
  • 2021-08-06
  • 2022-01-20
  • 2022-12-23
相关资源
相似解决方案