MySQL
 Computer >> コンピューター >  >> プログラミング >> MySQL

JDBCプログラムを使用してテーブルの特定の列を取得するにはどうすればよいですか?


ResultSet JDBCのインターフェースは、SQLクエリによって生成された表形式のデータを表します。現在の行を指すカーソルがあります。最初、このカーソルは最初の行の前に配置されます。

next()を使用してカーソルを移動できます メソッドと、ResultSetインターフェースのgetterメソッド(getInt()、getString()、getDate()など)を使用して行の列値を取得できます。

テーブルから必要なデータを取得するには:

  • データベースに接続します。

  • Statementオブジェクトを作成します。

  • executeQuery()を使用してステートメントを実行します 方法。このメソッドに、文字列形式で選択クエリを渡します。すべての値を取得するには、次のクエリを使用します。

Select * from TableName;
  • 特定の列を取得するには、*の代わりに必要な列名を次のように指定します。

select Name, DOB from Emp

データベースにEmpという名前のテーブルがあり、次の説明があるとします。

+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| Name     | varchar(255) | YES  |     | NULL    |       |
| DOB      | date         | YES  |     | NULL    |       | 
| Location | varchar(255) | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+

次のJDBCの例では、Empテーブルから従業員のName値とDOB値を取得します。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingParticularColumn {
      public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");

      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select Name, DOB from Emp");

      System.out.println("Contents of the table");
      while(rs.next()) {
         System.out.print("Name of the Employee: "+rs.getString("Name")+", ");
         System.out.print("Date of Birth: "+rs.getDate("DOB"));
         System.out.println("");
      }
   }
}

出力

Connection established......
Contents of the table
Name of the Employee: Amit, Date of Birth: 1970-01-08
Name of the Employee: Sumith, Date of Birth: 1970-01-08
Name of the Employee: Sudha, Date of Birth: 1970-01-05

  1. JDBCを使用してデータベースからファイルを取得するにはどうすればよいですか?

    ResultSet インターフェイスは、 getClob()という名前のメソッドを提供します およびgetCharacterStream() Clobを取得するには データ型。通常、ファイルの内容が保存されます。 これらのメソッドは、列のインデックスを表す整数(または、列の名前を表す文字列値)を受け入れ、指定された列の値を取得します。 違いは、getClob()メソッドがClobオブジェクトを返し、getCgaracterStream()メソッドがClobデータ型のコンテンツを保持するReaderオブジェクトを返すことです。 例 次の説明を使用して、データベースにArticlesとい

  2. getCharacterStream()メソッドを使用してテーブルからClob値を取得するJDBCの例を記述しますか?

    ResultSet インターフェイスは、データベース内のテーブルからclobデータ型を取得するためのgetClob()という名前のメソッドを提供します。これに加えて、getCharacterStream()という名前のメソッドも提供します。 getClob()と同様に、このメソッドも列のインデックスを表す整数(または、列の名前を表すString値)を受け入れ、指定された列の値を取得します。違いは、getClob()メソッド(Clobオブジェクトを返す)とは異なり、このメソッドはReaderクラスのオブジェクトを返します。 例 次の説明を使用して、データベースにMyDataという名前のテー