使用idea連接mysql數(shù)據(jù)庫(kù)并進(jìn)行查詢,是一件非常常見(jiàn)的開(kāi)發(fā)工作。在開(kāi)始之前,我們需要先確認(rèn)已經(jīng)安裝好了mysql數(shù)據(jù)庫(kù),并確保數(shù)據(jù)庫(kù)的說(shuō)明文檔已經(jīng)完整地編寫(xiě)好了。接下來(lái),我們就可以開(kāi)始使用idea進(jìn)行進(jìn)行數(shù)據(jù)庫(kù)的連接和查詢了。
//首先,我們需要在我們的代碼中引入mysql的驅(qū)動(dòng)包 import java.sql.*; //然后,我們就可以開(kāi)始連接數(shù)據(jù)庫(kù)了 public class main { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&characterEncoding=UTF-8&useUnicode=true&user=root&password=123456"); statement = connection.createStatement(); String sql = "select * from user"; resultSet = statement.executeQuery(sql); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String password = resultSet.getString("password"); System.out.println("id:" + id + ", name:" + name + ", password:" + password); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
代碼中當(dāng)中的路徑就是連接mysql服務(wù)器的路徑,根據(jù)自己電腦上的mysql安裝路徑進(jìn)行更改。在成功連接數(shù)據(jù)庫(kù)之后,我們就可以使用statement對(duì)象來(lái)執(zhí)行查詢命令,并利用resultSet對(duì)象來(lái)獲取查詢結(jié)果了。而finally語(yǔ)句塊則是用來(lái)釋放連接資源的,以免出現(xiàn)資源泄露的問(wèn)題。