Java 如何使用不同的行方法使用JDBC获取表中的行数
在这个数据驱动的世界中,与数据库交互的能力是许多软件程序的重要要求。Java是一种多功能和强大的编程语言,提供了Java数据库连接(JDBC),这是一种有效的机制,可以使不同的数据库系统平稳地与之交互。
JDBC是一个API,为Java应用程序提供了一个标准化的接口,用于与数据库进行通信。我们可以使用它作为Java应用程序和数据库之间的桥梁,执行查询、插入、更新和删除等操作。
本文将帮助我们深入了解Java的JDBC API世界,使我们能够利用其功能执行高效的数据库操作。
JDBC的重要组成部分包括:
- JDBC驱动器: JDBC驱动器的作用是连接数据库并将JDBC请求转换为特定于数据库的命令。确保为您的数据库系统选择正确的驱动程序,因为不同的数据库需要不同类型的驱动程序。
- JDBC API: JDBC API由用于执行数据库操作的方法和功能的类和接口组成。它包括用于连接数据库、运行SQL查询、获取和修改数据以及管理事务的类。
- JDBC URL: JDBC URL是一个唯一的字符串标识符,包含建立数据库连接的关键信息。这些信息包括数据库类型、主机、端口、数据库名称和登录凭据。
为了获得表中的行数,首先需要在MYSQL数据库中创建一个表,或者您可以使用您熟悉的任何数据库。
让我们创建一个表:
打开Mysql数据库,现在我们将创建一个新的数据库并使用它。
create database Test;
use Test;
现在让我们创建一个员工表,包括 emp_id、emp_name、emp_email。
查询
create table Employee(emp_id int primary key,emp_name varchar(20), emp_email varchar(20));
desc Employee;
输出
将一些记录插入到Employee表中:
insert into Employee values(1,"Hari","hari123@gmail.com");
insert into Employee values(2,"Syam","syam98@gmail.com");
insert into Employee values(3,"Revanth","Revanth53@gmail.com");
让我们来检查数据是否已经插入到表中:
查询
select *from Employee;
输出
现在我们拥有了数据。让我们创建一个Java应用程序,并尝试通过Eclipse IDE连接到这个数据库。创建Java应用程序后,我们需要使用JDBC驱动程序来获取在MySQL中创建的表中的行数。这个过程主要包括4个步骤:
- 建立连接。
-
创建语句。
-
执行SQL语句。
-
关闭连接。
在与数据库建立连接之前,我们需要加载JDBC驱动程序,或者只需从Maven仓库添加MySQL依赖项以建立连接,驱动程序类名将根据所使用的数据库而变化。
Class.forName("com.mysql.jdbc.Driver");
或
依赖关系
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
现在我们将使用JDBC URL、用户名和密码建立与数据库的连接。
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/Test","root", "root");
一旦连接建立好了,我们可以使用Statement或PreparedStatement类执行我们的SQL语句。
主要有两种方法可以从表中获取行数,其中大多数人使用的是最常见的方法:
select count(*) from Employee;
但这种方式效率较低,我们还有一种更快的方法来获取行数:
select count(1) from Employee;
这个查询使用第一列计算行数。由于主键通常是第一列,因此主键不为空且始终是唯一的。
示例1
在这个示例中,我们使用count(1)通过JDBC获取表中记录的总数。
import java.net.ConnectException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class App {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/Test";
String user ="root";
String password = "root";
Connection myConn = null;
ResultSet result = null;
try {
//We will provide the url,username and the password to establish the connection
myConn = DriverManager.getConnection(url,user,password);
//creating a statement
Statement myStmt = myConn.createStatement();
//Total Rows is nothing but Alias name
//and we will specify the query which we need to execute inside executeQuery()
result= myStmt.executeQuery("select count(1) as TotalRows from Employee");
//result.next() will executes the query
result.next();
//displaying the result i.e we will display number of rows in the table in console
System.out.println("Employee Table contains "+ result.getInt("TotalRows") + " rows");
}
catch(Exception e){
// this catch block is used to handle the exceptions
e.printStackTrace();
}
finally {
//close the connection
myConn=null;
result=null;
}
}
}
输出
Employee Table contains 3 rows
示例2
我们还有另一种方法可以使用resultSet.getRow()方法获取行数。
import java.net.ConnectException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class App {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/Test";
String user ="root";
String password = "root";
Connection myConn = null;
ResultSet result = null;
try {
//We will provide the url,username and the password to establish the connection
myConn = DriverManager.getConnection(url,user,password);
//creating a statement
//TYPE_SCROLL_SENSITIVE helps to move the cursor in forward or backward direction
//CONCUR_READ_ONLY means we cannot the update the resultSet only read is possible
Statement myStmt = myConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//Total Rows is nothing but Alias name
//and we will specify the query which we need to execute inside executeQuery()
result= myStmt.executeQuery("select * from Employee");
//result.next() will executes the query
result.last();
//displaying the result i.e we will display number of rows in the table in console
System.out.println("Employee Table contains " +result.getRow()+ " rows");
}
catch(Exception e){
// this catch block is used to handle the exceptions
e.printStackTrace();
}
finally {
//close the connection
myConn=null;
result=null;
}
}
}
输出
Employee Table contains 3 rows
结论
在本文中,我们探讨了使用JDBC获取表中总行数的方法和实现,并且我们还了解了JDBC的关键组件,它们能够与不同的数据库系统进行顺畅的交互。