📜  在JDBC中搜索表内容的Java程序

📅  最后修改于: 2022-05-13 01:54:31.422000             🧑  作者: Mango

在JDBC中搜索表内容的Java程序

为了处理 JDBC 标准,应该遵循 7 个步骤:

  1. 导入数据库
  2. 加载和注册驱动程序
  3. 创建连接
  4. 创建声明
  5. 执行查询
  6. 处理结果
  7. 关闭连接

程序:

  1. 导入数据库Java中导入sql数据库的语法是-
    导入Java.sql.* ;
  2. 加载和注册驱动程序- 加载驱动程序类后注册驱动程序的语法是
    forName(com.mysql.jdbc.xyz);
  3. 创建数据库而不管SQLNoSQL 。使用sqlyog创建数据库并在其中创建一些表并在其中填充数据以搜索表的内容。例如,数据库名为“hotelman”,表名为“cuslogin”和“adminlogin”。
  4. 创建连接:打开任何可以按照标准方法生成Java可执行文件的 IDE。创建包进一步创建类。在包内,打开一个新的Java文件并键入以下用于 JDBC 连接的代码并将文件名与 connection.json 一起保存。Java。
  5. 在表中搜索内容,假设我的“cuslogin”表包含“id”、“name”、“email”、“password”列,我们要搜索 id 为 1 的客户。
  6. 使用 SQL 查询初始化一个字符串,如下所示
String sql="select * from cuslogin where id=1";

如果我们想搜索任何一般的id,那么SQL查询就变成了

String sql="select * from cuslogin where id="+Integer.parseInt(textfield.getText());

文本字段是用户在“cuslogin”表中输入他想要搜索的 id 的区域(以 Jframe 形式)。

4.1:初始化Connection类、PreparedStatement类、ResultSet类(JDBC需要)的以下对象并连接数据库如下

Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
con = connection.connectDB();

4.2:现在,在prepareStatement里面添加步骤3.1的SQL查询,执行如下:

p =con.prepareStatement(sql);
rs =p.executeQuery();

4.3:我们检查 rs.next() 是否不为空,然后我们在“cuslogin”表中显示该特定客户的详细信息

4.4:在同一个包中打开一个新的Java文件(这里是它的结果Java)并输入完整代码(如下所示)以从表“cuslogin”中搜索id为1的客户的详细信息。

执行:

示例 1

连接类 JDBC通过在下面的1B中的main(App) Java程序中创建一个对象来调用

Java
// Java program to search the contents of
// a table in JDBC Connection class for JDBC
// Connection class of JDBC
  
// Importing required classes 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
  
public class connectionDB {
  
    final String DB_URL
        = "jdbc:mysql://localhost:3306/testDB?useSSL=false";
  
    //  Database credentials
  
    // We need two parameters to access the database
    // Root and password 
      
    // 1. Root 
    final String USER = "root";
      
    // 2. Password to fetch database
    final String PASS = "Imei@123";
  
    // Connection class for our database connectivity
   public Connection connectDB()
    {
        // Initially setting NULL
        // to connection class object
        Connection con = null;
  
        // Try block to check exceptions
        try {
  
            // Loading DB(SQL) drivers
            Class.forName("com.mysql.cj.jdbc.Driver");
  
            // Registering SQL drivers
            con = DriverManager.getConnection(DB_URL, USER,
                                              PASS);
        }
  
        // Catch block to handle database exceptions
        catch (SQLException e) {
  
            // Print the line number where exception occurs
            e.printStackTrace();
        }
  
        // Catch block to handle exception
        // if class not found
        catch (ClassNotFoundException e) {
  
            // Function prints the line number
            // where exception occurs
            e.printStackTrace();
        }
  
        // Returning Connection class object to
        // be used in (App/Main) GFG class
        return con;
    }
}


Java
// Java program to Search the
// contents of a table in JDBC
  
// Main Java program (App Class) of JDBC
  
// Step 1: Importing database files
// Importing SQL libraries
import java.sql.*;
  
// Main class
// It's connection class is shwon above
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Step 2: Establishing a connection
        connectionDB connection = new connectionDB();
  
        // Assigning NULL to object of Connection class
        // as shown returned by above program
        Connection con = null;
        PreparedStatement p = null;
        ResultSet rs = null;
  
        // Step 3: Loading and registereding drivers
        // Loaded and registered in Connection class
        // shown in above program
        con = connection.connectDB();
  
        // Try block to check exceptions
        try {
  
            // Step 4: Write a statement
            String sql
                = "select * from cuslogin where id=1";
  
            // Step 5: Execute the query
            p = con.prepareStatement(sql);
            rs = p.executeQuery();
  
            // Step 6: Process the results
            System.out.println(
                "id\t\tname\t\temail\t\tpassword");
  
            // Condition check using next() method
            // Holds true till there is single element remaining
          // in the object 
            if (rs.next()) {
                
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                String password = rs.getString("password");
                  
              // Print and display name, emailID and password 
              System.out.println(id + "\t\t" + name
                                   + "\t\t" + email + "\t\t"
                                   + password);
            }
        }
  
        // Catch block to handle exceptions
        catch (SQLException e) {
  
            // Print the exception
            System.out.println(e);
        }
    }
}



程序编译运行所在的App/Main Class调用上述连接类对象

Java

// Java program to Search the
// contents of a table in JDBC
  
// Main Java program (App Class) of JDBC
  
// Step 1: Importing database files
// Importing SQL libraries
import java.sql.*;
  
// Main class
// It's connection class is shwon above
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Step 2: Establishing a connection
        connectionDB connection = new connectionDB();
  
        // Assigning NULL to object of Connection class
        // as shown returned by above program
        Connection con = null;
        PreparedStatement p = null;
        ResultSet rs = null;
  
        // Step 3: Loading and registereding drivers
        // Loaded and registered in Connection class
        // shown in above program
        con = connection.connectDB();
  
        // Try block to check exceptions
        try {
  
            // Step 4: Write a statement
            String sql
                = "select * from cuslogin where id=1";
  
            // Step 5: Execute the query
            p = con.prepareStatement(sql);
            rs = p.executeQuery();
  
            // Step 6: Process the results
            System.out.println(
                "id\t\tname\t\temail\t\tpassword");
  
            // Condition check using next() method
            // Holds true till there is single element remaining
          // in the object 
            if (rs.next()) {
                
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                String password = rs.getString("password");
                  
              // Print and display name, emailID and password 
              System.out.println(id + "\t\t" + name
                                   + "\t\t" + email + "\t\t"
                                   + password);
            }
        }
  
        // Catch block to handle exceptions
        catch (SQLException e) {
  
            // Print the exception
            System.out.println(e);
        }
    }
}

输出:基于存储在“cuslogin”表中的值。