SQL Count()函数返回表中的行数。使用此方法,您可以获取表中的行数。
select count(*) from TABLE_NAME;
让我们使用CREATE语句在MySQL数据库中创建一个名称为cricketers_data 的表,如下所示-
CREATE TABLE cricketers_data( First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), );
现在,我们将使用INSERT语句在cricketers_data 表中插入5条记录-
insert into cricketers_data values('Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into cricketers_data values('Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into cricketers_data values('Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into cricketers_data values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into cricketers_data values('Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
以下JDBC程序建立与MySQL的连接,并在名为cricketers_data的表中显示行数。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Count_Example { public static void main(String args[]) throws Exception { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建Statement对象 Statement stmt = con.createStatement(); //查询以获取表中的行数 String query = "select count(*) from Cricketers_Data"; //执行查询 ResultSet rs = stmt.executeQuery(query); //检索结果 rs.next(); int count = rs.getInt(1); System.out.println("Number of records in the cricketers_data table: "+count); } }
输出结果
Connection established...... Number of records in the cricketers_data table: 5