一、配置MySQL數據庫連接器
在連接MySQL之前,首先需要下載MySQL JDBC Driver,將下載下來的jar文件放置到eclipse項目的Libraries中。
├── Libraries │ └── MySQL JDBC Driver.jar └── src
然後,在eclipse的菜單中選擇Window->Preferences->Data Management->Connectivity->Driver Definitions,點擊「New Driver Definition」添加MySQL的驅動。
填寫如下信息:
- Driver Name:MySQL JDBC Driver
- Database Type:MySQL
- Vendor:MySQL Connector/J
- JAR List:選擇MySQL驅動jar包
- Class Name:com.mysql.jdbc.Driver
二、創建數據庫連接
完成MySQL數據庫連接器的配置之後,即可創建MySQL數據庫連接,選擇菜單Window->Show View->Other->Data Management->Data Source Explorer,在Data Source Explorer窗口右鍵點擊「New」,選擇「Database Connection」
填寫如下信息:
- Connection profile:
- Driver:選擇MySQL JDBC Driver
- URL填寫其中一個數據庫地址:
- jdbc:mysql://localhost:3306/數據庫名
- jdbc:mysql://IP地址:3306/數據庫名
- User Name:填寫數據庫的用戶名
- Password:填寫數據庫密碼
點擊「Test Connection」測試是否連接成功,連接成功後點擊「OK」保存設置。
三、編寫Java程序連接MySQL數據庫
使用JDBC編寫Java代碼連接MySQL數據庫,示例如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MySQLConnectDemo { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { //加載MySQL的JDBC驅動 Class.forName("com.mysql.jdbc.Driver"); //建立MySQL連接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/數據庫名", "用戶名","密碼"); //創建Statement對象 statement = connection.createStatement(); //查詢表的數據 resultSet = statement.executeQuery("select * from table"); while (resultSet.next()) { //獲取每行數據 String column1 = resultSet.getString("column1"); String column2 = resultSet.getString("column2"); //輸出結果 System.out.println(column1 + "\t" + column2); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
四、總結
以上就是使用eclipse連接MySQL數據庫的全部步驟,需要注意的是,連接MySQL數據庫需要正確配置MySQL JDBC Driver和MySQL連接地址,另外,在Java程序中需要加載MySQL的JDBC驅動,建立MySQL連接,執行SQL語句以及關閉連接等操作。
原創文章,作者:SLZRG,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/317118.html