JDBC (Java Database Connectivity) הוא Java API שמנהל חיבור למסד נתונים, הוצאת שאילתות ופקודות וטיפול בערכות תוצאות המתקבלות ממסד הנתונים. JDBC שוחרר במסגרת JDK 1.1 בשנת 1997, היה אחד המרכיבים הראשונים שפותחו עבור שכבת ההתמדה של Java.
JDBC נתפס בתחילה כ- API בצד הלקוח, מה שמאפשר ללקוח Java לתקשר עם מקור נתונים. זה השתנה עם JDCB 2.0, שכלל חבילה אופציונלית התומכת בחיבורי JDBC בצד השרת. בכל מהדורת JDBC חדשה מאז הוצגו עדכונים הן לחבילת צד הלקוח ( java.sql
) והן לחבילת צד השרת ( javax.sql
). JDBC 4.3, הגרסה העדכנית ביותר נכון לכתיבת שורות אלה, שוחרר במסגרת Java SE 9 בספטמבר 2017.
מאמר זה מציג סקירה כללית של JDBC, ואחריו מבוא מעשי לשימוש ב- API של JDBC לחיבור לקוח Java עם SQLite, מסד נתונים יחסי קל.
איך JDBC עובד
פותח כחלופה לממשק ה- API מבוסס ODBC (Open Database Connectivity) מבוסס C, JDBC מציע ממשק ברמת תכנות המטפל במכניקה של יישומי Java המתקשרים עם מסד נתונים או RDBMS. ממשק JDBC מורכב משתי שכבות:
- ה- API של JDBC תומך בתקשורת בין יישום Java למנהל JDBC.
- מנהל ההתקן של JDBC תומך בתקשורת בין מנהל JDBC לבין מנהל ההתקן של מסד הנתונים.
JDBC הוא ה- API הנפוץ שאיתו קוד היישום שלך מתקשר. מתחת לזה נמצא מנהל ההתקן התואם JDBC עבור מסד הנתונים שבו אתה משתמש.
איור 1 הוא סקירה אדריכלית של JDBC בשכבת ההתמדה של Java.

באמצעות JDBC להתחברות למסד נתונים
אחת העובדות המאושרות של תכנות במערכת האקולוגית של ג'אווה היא שסביר להניח שתמצא מחבר מסד נתונים יציב של JDBC לכל מסד נתונים שתבחר. במדריך זה נשתמש ב- SQLite כדי להכיר את JDBC, בעיקר מכיוון שהוא כל כך קל לשימוש.
השלבים להתחברות למסד נתונים עם JDBC הם כדלקמן:
- התקן או אתר את מסד הנתונים שאליו ברצונך לגשת.
- כלול את ספריית JDBC.
- ודא שמנהל ההתקן JDBC הדרוש לך נמצא בדרך הכיתה שלך.
- השתמש בספריית JDBC כדי להשיג חיבור למסד הנתונים.
- השתמש בחיבור להוצאת פקודות SQL.
- סגור את החיבור כשתסיים.
נעבור את השלבים האלה יחד.
מציאת מנהל התקן JDBC
כדי למצוא מנהל התקן עבור מסד הנתונים שבו ברצונך להשתמש, פשוט בצע חיפוש באינטרנט עבור מסד הנתונים שלך ו- JDBC. לדוגמא, הקלדת " mysql jdbc driver
" תפעיל מנהל התקן עבור MySQL. אני מאתגר אותך למצוא מסד נתונים תואם Java ללא מנהל התקן JDBC!
שלב 1. הורד והתקן את SQLite
SQLite הוא בסיס נתונים קומפקטי מאוד. זה לא מיועד לשימוש בייצור, אבל הוא בחירה מצוינת לנסות דברים במהירות. SQLite משתמש בקובץ כמסד הנתונים הפונקציונלי שלו, מבלי לדרוש שום התקנת שירות או דמון.
כדי להתחיל עם הדגמה זו, המשך והורד את מסד הנתונים לדוגמה של SQLite. פתח את .db
הקובץ ושמור אותו במקום שלא תשכח.
קובץ זה מכיל גם בסיס נתונים פונקציונלי מבוסס קבצים, וגם סכמת דוגמה ונתונים שבהם אנו יכולים להשתמש.
SQL ו- JDBC
NoSQL זכה לפופולריות בעשור האחרון, אך מאגרי מידע יחסיים נותרים הסוג הנפוץ ביותר של מאגר נתונים שנמצא בשימוש. מסדי נתונים יחסיים הוא מאגר מובנה המורכב שולחנות עם עמודות ושורות. SQL (Structured Query Language) הוא נתוני השפה שאדריכלים משתמשים בהם בכדי ליצור, לקרוא, לעדכן ולמחוק רשומות חדשות במסד נתונים יחסי. JDBC הוא שכבת מתאם מג'אווה ל- SQL: הוא נותן למפתחי Java ממשק משותף לחיבור למסד נתונים, הנפקת שאילתות ופקודות וניהול תגובות.
שלב 2. ייבא את JDBC ליישום Java שלך
נוכל לבצע את הקידוד שלנו ב- IDE, אך קידוד ישירות בעורך טקסט ידגים טוב יותר את הפשטות של JDBC. כדי להתחיל, יהיה עליך להתקין JDK תואם למערכת ההפעלה שלך.
בהנחה שמתקינים את כלי המפתחים של פלטפורמת Java, נוכל להתחיל ביצירת תוכנית Java פשוטה. בעורך הטקסט שלך, הדבק את הקוד המוצג ברשימה 1. התקשר לקובץ זה WhatIsJdbc.java
.
רישום 1. תוכנית Java פשוטה
class WhatIsJdbc{ public static void main(String args[]){ System.out.println("Hello JavaWorld"); } }
עכשיו לקמפל את הקוד על ידי הזנת הפקודה: javac WhatIsJdbc.java
. הקומפילציה תפנה את WhatIsJdbc.class
הקובץ. לבצע את הקובץ משורת הפקודה עם הקריאה: java WhatIsJdbc
.
[ראה "מהו ה- JDK? מבוא לערכת המפתחים של Java" לקבלת מידע נוסף על אינטראקציה עם ה- JDK בשורת הפקודה.]
ברגע שיש לך תוכנית Java בסיסית, אתה יכול לכלול את ספריות JDBC. הדבק את הקוד מרישום 2 בראש תוכנית ה- Java הפשוטה שלך.
רישום 2. יבוא JDBC
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.Statement;
כל אחד מהיבואים הללו מספק גישה למחלקה המאפשרת את חיבור מסד הנתונים של Java רגיל:
Connection
מייצג את החיבור למסד הנתונים.DriverManager
משיג את החיבור למסד הנתונים. (אפשרות נוספת היאDataSource
, משמשת לאיחוד חיבורים.)SQLException
מטפל בשגיאות SQL בין יישום Java למסד הנתונים.ResultSet
וStatement
מודל קבוצות תוצאות הנתונים SQL ההצהרות.
נראה כל אחד מאלה לפעול בקרוב.
שלב 3. הוסף את מנהל ההתקן JDBC לשביל הכיתה שלך
לאחר מכן תוסיף את מנהל ההתקן של SQLite לשביל הכיתה שלך. JDBC הנהג הוא בכיתה מיישמת את ה- API JDBC עבור מסד נתונים ספציפיים.
הורד את מנהל ההתקן SQLite מ- GitHub. הקפד להשיג את .jar
הקובץ העדכני ביותר ולאחסן אותו במקום שתזכור.
The next time you execute your Java program, you will pull that .jar
file in via the classpath. There are several ways to set the classpath. Listing 3 shows how to do it using a command-line switch.
Listing 3. Executing SQLite driver on the Java classpath
java.exe -classpath /path-to-driver/sqlite-jdbc-3.23.1.jar:. WhatIsJdbc
Notice that we've set the classpath to point at the driver and the local directory; this way Java will still find our class file.
Step 4. Obtain a database connection
The classpath now has access to the driver. Now, change your simple Java application file to look like the program in Listing 4.
Listing 4. Using the JDBC Connection class to connect to SQLite
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.Statement; class WhatIsJdbc{ public static void main(String[] args) { Connection conn = null; try { String url = "jdbc:sqlite:path-to-db/chinook/chinook.db"; conn = DriverManager.getConnection(url); System.out.println("Got it!"); } catch (SQLException e) { throw new Error("Problem", e); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } } }
Compile and execute this code. Assuming all goes well, you will get an affirming message.
No suitable driver found?
If you've received an error that looks like "No suitable driver found for jdbc:sqlite
," then you need to revisit the classpath and make sure it points to the driver you downloaded. Failed driver connection is the most common stumbling block for beginners using JDBC. Don't sweat it; just fix it.
Now we're ready for some SQL commands.
Step 5. Query the database
With the live connection object in hand, we can do something useful, like querying the database. Listing 5 shows how to query SQLite using the JDBC Connection
and Statement
objects.
Listing 5. Querying the database with JDBC
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.Statement; class WhatIsJdbc{ public static void main(String[] args) { Connection conn = null; try { String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db"; conn = DriverManager.getConnection(url); Statement stmt = null; String query = "select * from albums"; try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String name = rs.getString("title"); System.out.println(name); } } catch (SQLException e ) { throw new Error("Problem", e); } finally { if (stmt != null) { stmt.close(); } } } catch (SQLException e) { throw new Error("Problem", e); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } } }
In Listing 5 we use our Connection
object to obtain a Statement
object: conn.createStatement()
. We then use this object to execute an SQL query: stmt.executeQuery(query)
.
The executeQuery
command returns a ResultSet
object, which we then use to iterate over the data with while (rs.next())
. In this example, you should see the album titles we've queried on as output.
Notice that we also closed the connection, via a call to conn.close()
.
Network connections with JDBC
The database connection string in Listing 5 is for a local connection: jdbc:sqlite:path-to-db-file/chinook/chinook.db
. To access the database via a network, the connection string would need to include the network URL and (usually) credentials for accessing it.
Doing more with JDBC
So far we've covered the basics of using JDBC to connect to a database and issue SQL commands. While Statements
s and ResultSet
s work well for common scenarios, you'll likely need additional options for larger or more complex applications. Fortunately, the JDBC library continues evolving to meet most database access needs.
PreparedStatements
One easy way to increase the flexibility of your code is to replace the Statement
class with PreparedStatement
, as shown in Listing 6.
Listing 6. Using JDBC PreparedStatements
String prepState = "insert into albums values (?, ?);"; PreparedStatement prepState = connection.prepareStatement(sql); prepState.setString(1, "Uprising"); prepState.setString(2, "Bob Marley and the Wailers "); int rowsAffected = preparedStatement.executeUpdate();
PreparedStatement
replaces Statement
's hard-coded values with question marks (?
). Using PreparedStatement
s optimizes your code for reuse: a PreparedStatement
is compiled only once, and can then be reused with a variety of parameters. As your code base grows, you simply insert new values into the statement, instead of hacking the string object itself.
Batch updates
Whenever an application has several updates to issue, doing them in batches can greatly benefit performance. The essence of batching is to take the multiple updates and collect them together, then issue them all at once. Listing 7 uses JDBC's batch methods to perform a batch update of several PreparedStatement
s.
Listing 7. Batching with PreparedStatement
prepState.setString(1, "Uprising"); prepState.setString(2, "Bob Marley and the Wailers"); preparedStatement.addBatch(); prepState.setString(1, "Wildflowers"); prepState.setString(2, "Tom Petty and the Heartbreakers"); preparedStatement.addBatch(); int[] rowsAffected = preparedStatement.executeBatch();
JDBC transactions
Transactions in relational databases allow for a set of updates to be wrapped in an interaction that either succeeds or fails altogether. The basics of using a transaction via JDBC are to tell the system to turn off auto-commit, and then manually tell the system to commit when you are done. By default, auto-commit is on, which means whenever an executeUpdate
or executeInsert
is run, the command is committed.
Listing 8 shows a small slice of a JDBC transaction.
Listing 8. JDBC transactions
connection.setAutoCommit(false); // Use executeUpdate multiple times connection.commit();
When connection.commit()
is encountered, all the updates wrapped inside will be attempted, and if any fail, they all will be rolled back.
There are many more features in JDBC 4.3 worth exploring, including using CallableStatement
for stored procedures, using DataSource
objects for improved application performance (especially via connection pooling), and converting a JDBC ResultSet to a Java Stream.
Database-specific features
Although every JDBC-compliant database offers the same core features for connecting and interacting with a database via SQL, some databases do more than others. As an example, Oracle DB offers result caching, which is not required by the JDBC specification. Here's an example:
conn.prepareStatement ("select /*+ result_cache */ * from employees where employee_id < : 1");
This example is taken from the documentation for Oracle's JDBC OCI Driver.
Conclusion
JDBC is one of Java's oldest APIs, providing an easy-to-use solution for one of the perennial needs of Java application development. Knowing just the few JDBC calls demonstrated in this article will get you started using JDBC to connect to virtually any database. Once you've got those commands down, you can begin to explore some of the more sophisticated options that have been built into JDBC.
בעוד JDBC מספיק ליישומים פשוטים יותר, בסופו של דבר רוב המפתחים יסתכלו על ה- Java Persistence API (JPA) על מנת לפתח שכבת גישה רשמית יותר לנתונים. JPA דורש עבודה מוקדמת יותר והבנה מתוחכמת יותר של ארכיטקטורת היישומים, אך היא מקנה לך שכבת גישה נתונים עקבית יותר, מבודדת ומוגדרת היטב. ראה את המלווה למאמר זה, "מהו JPA? מבוא ל- Java Persistence API" לקבלת מידע נוסף על פיתוח שכבת ההתמדה של נתונים עבור יישומי Java שלך.
סיפור זה, "מהו JDBC? מבוא לקישוריות מסדי נתונים של ג'אווה" פורסם במקור על ידי JavaWorld.