在Java程式設計中,如何搜尋表中的資料內容?假定資料庫名稱是:testdb
,其中有一個表:employee
,這個表中有4
條記錄。
建立資料庫表的語句 -
use testdb;
create table if not exists employees (
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
INSERT INTO Employees VALUES (100, 28, 'Max', 'Su');
INSERT INTO Employees VALUES (101, 25, 'Wei', 'Wang');
INSERT INTO Employees VALUES (102, 30, 'Kida', 'Su');
INSERT INTO Employees VALUES (103, 28, 'Kobe', 'Bryant');
以下方法使用sql的where
和like
條件語句來搜尋資料庫表中的資料。
package com.yiibai;
import java.sql.*;
public class SearchTableContents {
public static void main(String[] args) throws Exception {
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost/testdb?useSSL=false";
String User = "root";
String Passwd = "123456";
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("Class not found " + e);
}
Connection con = DriverManager.getConnection(DB_URL, User, Passwd);
Statement stmt = con.createStatement();
String query[] = { "SELECT * FROM employees where id = 101",
"select * from employees where first like 'Ma_'",
"select * from employees where last like 'Brya%'" };
for (String q : query) {
ResultSet rs = stmt.executeQuery(q);
System.out.print("Names for query " + q + " , Results : ");
while (rs.next()) {
String name = rs.getString("first");
System.out.print(name + " ");
}
System.out.println();
}
}
}
上述程式碼範例將產生以下結果。
Names for query SELECT * FROM employees where id = 101 , Results : Wei
Names for query select * from employees where first like 'Ma_' , Results :
Names for query select * from employees where last like 'Brya%' , Results : Kobe
註:如果JDBC驅動程式安裝不正確,將獲得
ClassNotfound
異常。
Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
JDBC Class found
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/testdb